Remove Digit From Number to Maximize Result - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: number = "123", digit = "3"
Output: "12"
💡 Note: Only one occurrence of '3' at the end. Removing it gives "12".
Example 2 — Multiple Occurrences
$ Input: number = "1231", digit = "1"
Output: "231"
💡 Note: Two occurrences of '1' at positions 0 and 3. Removing position 0 gives "231", removing position 3 gives "123". "231" > "123", so return "231".
Example 3 — Remove for Maximum
$ Input: number = "551", digit = "5"
Output: "51"
💡 Note: Two occurrences of '5'. Removing first gives "51", removing second gives "55". "55" > "51", but we want to maximize by removing the optimal occurrence, which is the first one to get "51".

Constraints

  • 1 ≤ number.length ≤ 1000
  • number consists of digits
  • digit is a digit character
  • digit occurs at least once in number

Visualization

Tap to expand
Remove Digit From Number to Maximize Result INPUT String number: 1 2 3 idx: 0 idx: 1 idx: 2 Target digit to remove: 3 Input Values number = "123" digit = "3" ALGORITHM STEPS 1 Scan left to right Find digit occurrences 2 Greedy check If digit < next char, remove it 3 Otherwise continue Keep last occurrence position 4 Remove best digit Return resulting string Greedy Scan Process: i=0: '1' (not target) i=1: '2' (not target) i=2: '3' == digit [FOUND] Remove at index 2 FINAL RESULT After removing digit '3': Before: 1 2 3 After: 1 2 Output "12" OK - Maximized value! Key Insight: The greedy approach removes the first occurrence of the target digit where digit[i] < digit[i+1]. This maximizes the result by promoting larger digits to higher positions. If no such position exists, remove the last occurrence of the target digit (as in this example where '3' is at the end). TutorialsPoint - Remove Digit From Number to Maximize Result | Greedy Removal Approach
Asked in
Google 25 Amazon 20 Microsoft 15
28.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen