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
.
For example:
number = "123"
, and digit = "3"
, the output should be "12"
because there is only one '3' to remove.number = "1231"
, and digit = "1"
, the output should be "231"
because removing the first '1' gives 231, and removing the second '1' gives 123. 231 > 123.number = "551"
, and digit = "5"
, the output should be "51"
because removing either of the '5's results in the same string.The most straightforward approach is to iterate through the string number
, identify all occurrences of the digit digit
, and for each occurrence, create a new string by removing that digit. Then, compare all the resulting strings and return the lexicographically largest one.
def remove_digit_naive(number: str, digit: str) -> str:
results = []
for i in range(len(number)):
if number[i] == digit:
results.append(number[:i] + number[i+1:])
return max(results)
A more efficient approach is to iterate through the string number
and remove the digit
such that the remaining string is maximized. This can be achieved by removing the first occurrence of digit
where the next digit is greater than the current digit
. If no such digit
is found, remove the last occurrence of digit
.
def remove_digit_optimal(number: str, digit: str) -> str:
last_occurrence = -1
for i in range(len(number)):
if number[i] == digit:
last_occurrence = i
if i < len(number) - 1 and number[i] < number[i + 1]:
return number[:i] + number[i + 1:]
return number[:last_occurrence] + number[last_occurrence + 1:]
last_occurrence
variable.last_occurrence
variable ensures this works.last_occurrence
variable.The optimal solution provides a more efficient way to solve the problem by iterating through the string once and making a decision on the fly. The naive solution, while simpler to understand, has a higher time complexity because it involves creating multiple strings and comparing them.