Home
DSA Patterns
Stack
Remove K Digits
Remove K Digits (LeetCode 402)
Remove k digits to make the smallest number with a greedy monotonic stack: drop a digit whenever a smaller one comes after it.
Problem Understanding
Remove K Digits: given a non-negative integer as a string num and an integer k, remove exactly k digits so the remaining number is as small as possible. Return it without leading zeros, or "0".
Example: num = "1432219", k = 3 returns "1219": removing 4, 3 and 2 does it.
The Intuition: Small Digits Belong on the Left
The leftmost digit matters most. Whenever a digit is followed by a smaller one, removing it improves the number at that position, so do it greedily. A stack makes this one pass, and it stays non-decreasing, like every monotonic stack:
- For each digit
d, while removals remain and the top is bigger thand, pop the top (one removal). - Push
d. - If removals are left, the digits never fall, so drop them from the end.
- Strip leading zeros; an empty result is
"0".
The pop rule is the same "top loses to the newcomer" loop as Next Greater Element I, with a budget of k pops.
Remove K Digits Visualization
EMPTY STACK
num
0
1
2
3
4
5
6
kept digits (stack, top on the right)
EMPTY
k left
3
kept
0
Answer
:
Remove 3 digits from 1432219 to make it as small as possible. Keep the kept digits on a stack
Next
Keep 1
num
k
The digits of num are on top; below them, the digits kept on the stack. A removed digit turns red for one step. Try Example 2 for the leading-zero case and Rising for removals taken off the end.
Remove K Digits Dry Run
Input: num = "1432219", k = 3
| Digit | Removed | k left | Stack after |
|---|---|---|---|
| 1 | - | 3 | 1 |
| 4 | - | 3 | 14 |
| 3 | 4 | 2 | 13 |
| 2 | 3 | 1 | 12 |
| 2 | - | 1 | 122 |
| 1 | 2 | 0 | 121 |
| 9 | - | 0 | 1219 |
Answer: "1219".
Remove K Digits LeetCode Solution
A stack of kept digits, popped while removals remain and the top is bigger.
Remove K Digits Code
1var removeKdigits = function(num, k) {2 const stack = [];3 for (const d of num) {4 while (k && stack.length && stack[stack.length - 1] > d) {5 stack.pop();6 k--;7 }8 stack.push(d);9 }10 stack.length -= k;11 return stack.join('').replace(/^0+/, '') || '0';12};
Remove K Digits in Python, Java, C++, TypeScript and C
Remove K Digits in Python
class Solution:
def removeKdigits(self, num: str, k: int) -> str:
stack = []
for d in num:
while k and stack and stack[-1] > d:
stack.pop()
k -= 1
stack.append(d)
while k:
stack.pop()
k -= 1
return ''.join(stack).lstrip('0') or '0'Remove K Digits in Java
class Solution {
public String removeKdigits(String num, int k) {
StringBuilder stack = new StringBuilder();
for (char d : num.toCharArray()) {
while (k > 0 && stack.length() > 0 && stack.charAt(stack.length() - 1) > d) {
stack.deleteCharAt(stack.length() - 1);
k--;
}
stack.append(d);
}
stack.setLength(stack.length() - k);
int i = 0;
while (i < stack.length() - 1 && stack.charAt(i) == '0') i++;
return stack.length() == 0 ? "0" : stack.substring(i);
}
}Remove K Digits in C++
class Solution {
public:
string removeKdigits(string num, int k) {
string stack;
for (char d : num) {
while (k && !stack.empty() && stack.back() > d) {
stack.pop_back();
k--;
}
stack.push_back(d);
}
stack.resize(stack.size() - k);
size_t i = stack.find_first_not_of('0');
return i == string::npos ? "0" : stack.substr(i);
}
};Remove K Digits in TypeScript
function removeKdigits(num: string, k: number): string {
const stack: string[] = [];
for (const d of num) {
while (k && stack.length && stack[stack.length - 1] > d) {
stack.pop();
k--;
}
stack.push(d);
}
stack.length -= k;
return stack.join('').replace(/^0+/, '') || '0';
}Remove K Digits in C
char* removeKdigits(char* num, int k) {
int n = strlen(num), top = 0;
char* stack = malloc(n + 2);
for (int i = 0; i < n; i++) {
while (k && top && stack[top - 1] > num[i]) {
top--;
k--;
}
stack[top++] = num[i];
}
top -= k;
int start = 0;
while (start < top && stack[start] == '0') start++;
if (start == top) return "0";
stack[top] = '\0';
return stack + start;
}Edge Cases & Common Mistakes
- k equals the length: everything goes; return
"0", not an empty string. - Leading zeros:
"10200", k = 1 leaves"0200"; strip to"200". - Non-decreasing input: nothing is popped in the loop; the leftover removals must come off the end.
- Equal digits: do not pop on equal (
>not≥); removing one of two equal digits gains nothing there. - Converting to an integer: num can have up to 10⁵ digits; keep it as a string.
Summary
Walk the digits with a stack, popping a bigger top while removals remain, then push. Spend leftover removals on the end, strip leading zeros, and return "0" if nothing is left. O(n) time, O(n) space.
More practice: DSA interview questions with answers · patterns cheat sheet
