LeetCode 2259. Remove Digit From Number to Maximize Result Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
2259. Remove Digit From Number to Maximize Result

Description

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 <= 100
  • number consists of digits from '1' to '9'.
  • digit is a digit from '1' to '9'.
  • digit occurs at least once in number.

Solutions

Solution 1: Brute Force Enumeration

We can enumerate all positions i in the string number. If number[i] = digit, we take the prefix number[0:i] and the suffix number[i+1:] of number and concatenate them. This gives the result after removing number[i]. We then take the maximum of all possible results.

The time complexity is O(n2), and the space complexity is O(n). Here, n is the length of the string number.

PythonJavaC++GoTypeScriptPHP
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 )(code-box)

Solution 2: Greedy

We can enumerate all positions i in the string number. If number[i] = digit, we record the last occurrence position of digit as last. If i + 1 < n and number[i] < number[i + 1], then we can directly return number[0:i] + number[i+1:] as the result after removing number[i]. This is because if number[i] < number[i + 1], removing number[i] will result in a larger number.

After the traversal, we return number[0:last] + number[last+1:].

PythonJavaC++Go
class Solution: def removeDigit(self, number: str, digit: str) -> str: last = -1 n = len(number) for i, d in enumerate(number): if d == digit: last = i if i + 1 < n and d < number[i + 1]: break return number[:last] + number[last + 1 :](code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !