Best Result After Removing a Single Five from a Number String
Greedy & IntervalsAuto-graded · 26 test casesLast updated
Remove exactly one '5' from a digit string to get the lexicographically largest result of equal length, using a greedy scan and preserving leading zeros.
Remove One Five
You receive a string num_str consisting only of decimal digit characters. It is guaranteed to contain at least one '5'.
You must remove exactly one '5' from the string. The other characters stay in their original relative order. Return the resulting string that represents the largest possible number.
Details
- Exactly one
'5'is removed. Nothing else is deleted, inserted or rearranged. - Every candidate result has length
len(num_str) - 1, so comparing two candidates as numbers gives the same answer as comparing them character by character from the left. - Return the result as a string and keep any leading zeros that appear after the removal. For instance, removing the only
'5'from"503"gives"03". - Different removals may produce identical strings (removing either
'5'from"55"gives"5"). The answer is the resulting string, so it is always well defined.
Constraints
2 <= len(num_str) <= 100000- Every character of
num_stris a digit from'0'to'9'. num_str[0] != '0'num_strcontains at least one'5'.
Examples
Example 1
Input: remove_five_for_max('15958')
Output: '1958'
Example 2
Input: remove_five_for_max('5505')
Output: '550'
Example 3
Input: remove_five_for_max('503')
Output: '03'
Hints
Hint 1
All candidate results have the same length, so the leftmost position where two candidates differ decides which is bigger. Avoid converting to int.
Hint 2
Removing a '5' at index i shifts everything after it one place left, so position i now holds the next character. Ask when that is an improvement over keeping the '5' there.
Hint 3
If no '5' is followed by a larger digit, every removal either hurts or ties at its position, so think about which '5' to remove to disturb the string as far right as possible.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Removing the '5' at index i keeps everything before i unchanged and shifts everything after it one place to the left. So the first position that can change is i itself, where the '5' is replaced by the character that followed it.
Since all candidates have the same length, the leftmost difference decides the winner. This leads to a greedy rule:
- Scan left to right. At the first
'5'that is immediately followed by a digit greater than'5', remove it. The string improves at the earliest possible position. - If there is no such
'5', remove the last'5'. Any removal then either lowers the string or leaves it equal at the point of change, so disturbing it as far right as possible keeps the longest prefix intact.
Why it is correct
Take two '5' positions i < j, and let A and B be the results of removing i and j respectively. They agree before index i and from index j onward. Between i and j they differ first at the end of the run of consecutive '5's that starts at i, where A has the character after the run and B still has a '5'. If that character is larger than '5', A wins; if it is smaller, B wins; if the run reaches j, the strings are identical.
- If some
'5'is followed by a larger digit, the first such one beats every later'5', and beats earlier ones (which are followed by smaller digits at the end of their runs, or tie with it). - Otherwise, every earlier
'5'either loses to the last'5'or ties with it, so removing the last one is optimal.
Removing any '5' within the same run gives the same string, so tie-breaking does not matter.
Complexity
- Time: O(n), one scan plus one slice-and-concatenate.
- Space: O(n) for the output string.
Generating every candidate and taking the maximum would cost O(n * m) for m fives, which is too slow for n = 100000. Converting to int is also wrong since it drops leading zeros.
Reference solution
def remove_five_for_max(num_str: str) -> str:
n = len(num_str)
last = -1
for i in range(n):
if num_str[i] == "5":
if i + 1 < n and num_str[i + 1] > "5":
return num_str[:i] + num_str[i + 1:]
last = i
return num_str[:last] + num_str[last + 1:]