mediumMonotonic StackGreedyStack

Remove K Digits

mediumTime: O(n)Space: O(n)

Recognize the pattern

remove k digits to make smallest numbermonotonic increasing preferredgreedy digit removal

Brute force idea

A straightforward first read of Remove K Digits is this: Try all combinations of k digit removals. Combinatorial explosion. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.

Better approach

The real unlock in Remove K Digits comes when you notice this: Monotonic increasing stack: scan left to right. While the stack top > current digit and k > 0, pop (remove that digit). Push current digit. After processing, remove remaining k from the end. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.

Key invariant

The compass for Remove K Digits is this: A number is smallest when its digits are as small as possible from left to right. Removing a larger digit that precedes a smaller one always reduces the number — the stack greedily enforces non-decreasing order. As long as that statement keeps holding, you can trust the steps built on top of it.

Watch out for

A common way to get lost in Remove K Digits is this: Not handling leading zeros — after building the result, strip leading zeros. Also handle the edge case where the result is empty (return '0'). Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.

Stack Pattern