We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Remove Digit From Number to Maximize Result

Difficulty: Easy


Problem 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.


Key Insights

  • Removing a digit can potentially increase the overall value of the resulting number.
  • To maximize the resulting number, we should consider the position of the digit to be removed.
  • If the digit appears multiple times, we must evaluate the impact of removing different occurrences on the final value.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the number string, as we may need to check each character. Space Complexity: O(1), we are using a constant amount of extra space for variables.


Solution

To solve the problem, we can use a greedy approach. We will iterate through the string and for each occurrence of the digit, we will assess the impact of removing that digit. We will check the resulting numbers after removal and keep track of the maximum value. The steps are as follows:

  1. Initialize a variable to track the maximum resulting number.
  2. Loop through each character in the string:
    • If the character matches the digit, create a new string by removing that character.
    • Compare this new string with the current maximum; if it's greater, update the maximum.
  3. Return the maximum resulting string after considering all possible removals.

Code Solutions

def removeDigit(number: str, digit: str) -> str:
    max_result = ""
    for i in range(len(number)):
        if number[i] == digit:
            # Create a new number by removing the current digit
            new_number = number[:i] + number[i+1:]
            # Update max_result if the new number is greater
            if new_number > max_result:
                max_result = new_number
    return max_result
← Back to All Questions