Editor

Smallest Number After Deletions

#149 · Stacks and queues · Advanced · 135 XP · about 25 min

You are given a whole number as a string of digits and must cross out exactly k of its digits. The digits that remain keep their order and form a new number. Write remove_k_digits(num, k) that returns the smallest number you can make, as a string.

Leading zeros are dropped from the answer ("0200" becomes "200"), and if no digits are left, or only zeros, the answer is "0".

Examples

remove_k_digits("4381", 2)    # returns '31'
remove_k_digits("10200", 1)   # returns '200'
remove_k_digits("123456", 3)  # returns '123'
remove_k_digits("9", 1)       # returns '0'

For "4381" with two deletions, the possible results are 43, 48, 41, 38, 31 and 81, and 31 is the smallest.

Constraints

  • 1 <= len(num) <= 100,000
  • 0 <= k <= len(num)
  • num has no leading zeros, except for the number "0" itself.

Ready?

Accept the challenge to start writing. A small timer counts the time this page is in view.

Output appears here.