Algo-Sim › Stacks & Monotonic Stack
Remove K Digits
Medium · Stacks & Monotonic Stack · step through it in Java, Python and C++ on your own input
Keep an increasing stack of digits: pop a larger digit while removals are left, drop leading zeros, and trim the tail.
Problem
The string num is a non-negative integer and k is how many of its digits to remove. Return the smallest possible number, as a string, after removing exactly k digits. The result has no leading zeros, and is "0" if nothing is left.
Constraints
- 1 ≤ k ≤ num.length ≤ 10⁵
- num is digits only, with no leading zeros except the number 0 itself
Edge cases to test
- k equals the length:
"0" - Leading zeros after removal:
"10200", k = 1 →"200" - Already increasing: drop from the end
Follow-up questions
- Why is removing the first descent greedy-optimal?
- A smaller digit earlier always makes a smaller number, so popping a larger digit before it is never worse.
- What about the largest number instead?
- Keep a decreasing stack instead, removing a smaller digit before a larger one.
Solution
Java
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--;
}
if (stack.length() > 0 || d != '0') stack.append(d);
}
stack.setLength(Math.max(0, stack.length() - k));
return stack.length() == 0 ? "0" : stack.toString();
}Python
def remove_kdigits(num, k):
stack = []
for d in num:
while k > 0 and stack and stack[-1] > d:
stack.pop()
k -= 1
if stack or d != '0': stack.append(d)
del stack[max(0, len(stack) - k):]
return ''.join(stack) or '0'C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
string removeKdigits(string num, int k) {
string stack = "";
for (char d : num) {
while (k > 0 && !stack.empty() && stack.back() > d) {
stack.pop_back();
k--;
}
if (!stack.empty() || d != '0') stack.push_back(d);
}
stack.resize(max(0, (int)stack.size() - k));
return stack.empty() ? "0" : stack;
}
};
More Stacks & Monotonic Stack problems
- Valid Parentheses (Easy)
- Implement Queue using Stacks (Easy)
- Evaluate Reverse Polish Notation (Medium)
- Basic Calculator II (Medium)
- Basic Calculator (Hard)
- Decode String (Medium)
- Asteroid Collision (Medium)
- Next Greater Element (Easy)
- Daily Temperatures (Medium)
- Online Stock Span (Medium)
- Car Fleet (Medium)
- Largest Rectangle in Histogram (Hard)
- Maximal Rectangle (Hard)
- Sliding Window Maximum (Hard)