Problem Statement
Remove K Digits
You are given a string num that holds a non-negative whole number (like "1432219") and a number k. Your job is to delete exactly k digits from num so that the number left over is as small as possible. Here is the trick that makes this work. A number is read left to right, and the digits on the left count for the most. So to shrink the number, we want the early digits to be as small as we can make them. When we are scanning along and we hit a digit that is smaller than the one right before it, that earlier larger digit is hurting us, and deleting it makes the number smaller. To do this cleanly we use a stack. A stack is like a pile of plates: you add a plate to the top and you take a plate from the top, so the last one you put on is the first one you take off. Here we keep the digits we want to keep in the stack, and whenever a new smaller digit shows up, we pop the larger digits off the top and throw them away.
Signals to notice
Brute force first
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.
The key insight
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.
Trace it on num="1432219", k=3
digit 1: stack empty -> push. stack=[1], k=3 digit 4: top 1<4, no pop -> push. stack=[1,4], k=3 digit 3: top 4>3 pop(k=2), 1<3 stop -> push. stack=[1,3], k=2 digit 2: top 3>2 pop(k=1), 1<2 stop -> push. stack=[1,2], k=1 digit 2: top 2==2, no pop -> push. stack=[1,2,2], k=1 digit 1: top 2>1 pop(k=0), k=0 stop -> push. stack=[1,2,1], k=0 digit 9: k=0, push. stack=[1,2,1,9], k=0 k=0 so no end-trim; join -> "1219", strip zeros -> return "1219"
What must stay true
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.
Shape of the loop
stack = []
for digit in num:
while k > 0 and stack and stack.top > digit:
stack.pop(); k -= 1
stack.push(digit)
return strip_leading_zeros(stack[: len(stack) - k]) or "0"Pseudocode only — the full worked solution lives in the Solution tab.
Easy way to go wrong
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.