Remove Digit From Number to Maximize Result Problem
Description
LeetCode Problem 2259.
You are given a string number representing a positive integer and a character digit.
Return the resulting string after removing exactly one occurrence of digit from number such that the value of the resulting string in decimal form is maximized. The test cases are generated such that digit occurs at least once in number.
Example 1:
Input: number = "123", digit = "3"
Output: "12"
Explanation: There is only one '3' in "123". After removing '3', the result is "12".
Example 2:
Input: number = "1231", digit = "1"
Output: "231"
Explanation: We can remove the first '1' to get "231" or remove the second '1' to get "123".
Since 231 > 123, we return "231".
Example 3:
Input: number = "551", digit = "5"
Output: "51"
Explanation: We can remove either the first or second '5' from "551".
Both result in the string "51".
Constraints:
2 <= number.length <= 100numberconsists of digits from'1'to'9'.digitis a digit from'1'to'9'.digitoccurs at least once innumber.
Solution
Approach: Brute Force Enumeration
Try every position i where number[i] == digit, build the string without that character, and keep the largest. All candidates have the same length, so comparing them as strings gives the same order as comparing them as numbers.
Complexity: O(n^2) time and O(n) space, where n is the length of number.
Approach: Greedy
Removing a digit is best when the digit after it is larger, because that raises the number at the earliest possible position. So scan left to right: remember the latest occurrence of digit, and stop at the first occurrence that is followed by a larger digit. If there is no such occurrence, every occurrence is followed by an equal or smaller digit (or is the last one), and removing the last occurrence is best. Remove the remembered position.
Complexity: O(n) time and O(1) extra space.
class Solution:
def removeDigit(self, number: str, digit: str) -> str:
return max(
number[:i] + number[i + 1 :] for i, d in enumerate(number) if d == digit
)