0:00 / 0:00

Delete k digits to make the smallest number. Keep a rising stack and pop any bigger digit before a smaller one while deletions remain.

▼

The problem

LeetCode 402 (Medium). Given a non-negative integer as a string num and an integer k, remove k digits so the number left is as small as possible. The answer has no leading zeros, and an empty result is "0".

Examples (LeetCode's): "1432219", k = 3 → "1219" (the example and the walkthrough); "10200", k = 1 → "200" (the leading-zero loose end); "10", k = 2 → "0" (the code demo).

TRY IT ON LEETCODE ▶

The solution

def remove_k_digits(num, k):
    stack = []
    for d in num:
        while k and stack and stack[-1] > d:
            stack.pop()
            k -= 1
        stack.append(d)
    if k:
        stack = stack[:-k]
    return "".join(stack).lstrip("0") or "0"

Transcript

Remove K Digits. You get a number written as a string, and a count k. Remove exactly k digits so the number that's left is as small as possible. No leading zeros, and if nothing is left, the answer is zero.

Take one, four, three, two, two, one, nine, with k equal to three. The smallest you can leave is one, two, one, nine.

The slow way tries every set of k digits to remove. Seven choose three is thirty five tries, each built and compared. For long numbers, that count explodes.

The key idea is greedy. Digits on the left weigh the most. A four in the hundreds place costs more than anything after it. So when a digit is bigger than the next one, removing it always helps. Keep the digits in a stack that only rises. When a smaller digit arrives and removals remain, pop the bigger top, again and again. It's a monotonic stack, used greedily.

Let's run it with three removals. One goes on, then four. Three arrives: four is bigger, so pop it. Two arrives: pop the three. The next two is equal, so it stays. One pops a two: that was the last removal. One and nine just go on. Answer: one, two, one, nine.

Two loose ends. If removals are left over, the stack is rising, so the biggest digits sit at the end: cut them there. Then strip leading zeros. One, zero, two, zero, zero, with one removal, becomes two hundred.

In code, loop over the digits. While removals remain and the top is bigger, pop it and spend one. Then push the digit. After the loop, cut any leftovers from the end, strip the zeros, and return zero if it's empty.

Each digit is pushed once and popped at most once, so the time is linear. The stack can hold every digit, so the space is linear too.

Scan left to right, pop the bigger tops, trim the end, strip the zeros. That's Remove K Digits.