Remove K Digits
Difficulty: Medium · Pattern: Stack & Monotonic Stack · LeetCode #402
Given a non-negative integer as a string num, remove exactly k digits so the result is the smallest possible number. Return it without leading zeros ("0" if empty).
Examples
text
num = "1432219", k = 3 → "1219"
num = "10200", k = 1 → "200"
num = "10", k = 2 → "0"Hints
- Earlier digits matter more. If a digit is larger than the next one, removing it makes the number smaller.
- Greedily keep the digits non-decreasing using a stack.
Approach
For each digit, while k > 0 and the stack top is greater than the digit, pop (removing that digit) and decrement k. Push the digit. If k remains (a non-decreasing tail), remove from the end. Strip leading zeros; return "0" if nothing is left. Each digit is pushed and popped at most once, so O(n).
Complexity
Time: O(n). Space: O(n).
Python solution
def removeKdigits(num, k):
st = []
for d in num:
while k and st and st[-1] > d:
st.pop(); k -= 1
st.append(d)
if k:
st = st[:-k]
return "".join(st).lstrip("0") or "0"JavaScript solution
function removeKdigits(num, k) {
const st = [];
for (const d of num) { while (k && st.length && st[st.length - 1] > d) { st.pop(); k--; } st.push(d); }
while (k-- > 0) st.pop();
const s = st.join('').replace(/^0+/, '');
return s || '0';
}