Python coding

Smallest number after removing k digits

num is a non-negative integer written as a string of digits, with no leading zeros (except "0" itself). Remove exactly k of its digits, keeping the others in their original order, so that the number left is as small as possible. Return it as a string without leading zeros; if no digits are left, return "0".

Constraints: 0 <= k <= len(num). Aim for O(n).

Besides the tests, one large input (6,000 digits, remove 3,000) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • smallest_after_removal("2751386", 3) → "1386"
  • smallest_after_removal("30408", 1) → "408"
  • smallest_after_removal("52", 2) → "0"
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

To make a number smaller, fix its leftmost digits first. Which digit should go when a digit is followed by a smaller one?

Hint 2

Keep a stack of the digits you keep. Before pushing a digit, pop while the top is strictly greater and you still have removals left: the stack never decreases.

Hint 3

If removals are left after the scan, cut that many digits from the end. Then strip leading zeros, and return "0" if nothing remains.

Solution and why it works
pythonO(n) · O(n)
def smallest_after_removal(num: str, k: int) -> str:
    stack = []                                 # kept digits, never decreasing
    for d in num:
        while k and stack and stack[-1] > d:   # a bigger digit right before a smaller one
            stack.pop()
            k -= 1
        stack.append(d)
    if k:
        stack = stack[:-k]                     # no drop left to fix: cut from the end
    return "".join(stack).lstrip("0") or "0"

A smaller digit in an earlier position always wins, so whenever a digit is larger than the one after it, dropping it is the best use of a removal. The stack keeps the chosen digits in non-decreasing order; each digit is pushed once and popped at most once. Three traps: pop only on strictly greater (equal digits gain nothing), spend leftover removals at the end when the digits never drop, and strip leading zeros, returning "0" for an empty result.