KatInterview

Best Result After Removing a Single Five from a Number String

Greedy & IntervalsAuto-graded · 26 test cases
MediumAuto-gradedGreedy & Intervalsgreedystringsdigits

Last 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_str is a digit from '0' to '9'.
  • num_str[0] != '0'
  • num_str contains 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.