#2259

Remove Digit From Number to Maximize Result

Easy
StringGreedyEnumerationGreedyEnumeration
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(n)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution iterates through the string once, checking each occurrence of the digit and deciding whether removing it yields a larger number. This avoids unnecessary string creations and comparisons.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a variable to store the best result as an empty string.
  2. 2Step 2: Iterate through each character in the string number.
  3. 3Step 3: When the character matches the digit, create a new string without that character.
  4. 4Step 4: Compare this new string with the current best result and update if it's larger.
  5. 5Step 5: Return the best result after the loop.
solution.py8 lines
1def removeDigit(number: str, digit: str) -> str:
2    best_result = ''
3    for i in range(len(number)):
4        if number[i] == digit:
5            new_number = number[:i] + number[i+1:]
6            if new_number > best_result:
7                best_result = new_number
8    return best_result

Complexity note: The time complexity is O(n) because we only traverse the string once. The space complexity is O(1) since we only store a few variables, not dependent on the input size.

  • 1Removing a digit can lead to different results based on its position, especially if there are multiple occurrences.
  • 2The best result is determined by comparing all possible outcomes, but an optimal approach minimizes unnecessary comparisons.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.