Remove K Digits solution explained
Remove K Digits gives you a non-negative number as a string of digits and asks for the smallest number you can get by deleting exactly k digits while keeping the rest in order. The greedy rule is to delete a digit whenever the digit after it is smaller, as far to the left as possible, and a stack applies that rule in one left-to-right pass: pop larger digits while removals remain, then trim any leftover removals from the end and strip leading zeros. It runs in O(n) time.
By Evin JohnPublished 8 min read
Restating the problem
You get a number written as a string, such as "4271", and an integer k no larger than the string's length. Remove exactly k of its digits. The digits you keep stay in their original order and form a new number. Return the smallest number that can be formed this way, written without leading zeros, and return "0" when the result is empty or made only of zeros. The input itself has no leading zeros unless it is the single digit 0.
"4271", k = 2 -> "21" (drop 4 and 7)
"30500", k = 1 -> "500" (drop 3; "0500" loses its leading zero)
"1189", k = 2 -> "11" (no digit is followed by a smaller one, so cut the end)
"52", k = 2 -> "0" (everything removed)
"7000", k = 1 -> "0" (drop 7; "000" is zero)Ask early whether the number can be longer than any built-in integer type. It usually can, which is why the answer is a string and why converting to an int is a trap. Also ask whether k can equal the length (yes, and the answer is then "0").
What it tests
Remove K Digits is a greedy problem that needs a short argument, and a stack problem that does not look like one. Interviewers want to hear why removing a particular digit is safe, not just a rule recited from memory. The question also has three separate cleanup steps (leftover removals, leading zeros, empty result) that quietly test whether you finish the job after the main idea works.
Slow but sure: try every choice
Every answer is a choice of which n - k positions to keep, so you can try all of them and keep the smallest. Since every candidate has exactly n - k digits before cleanup, comparing them as strings gives the same order as comparing them as numbers. The cost is the number of combinations, which explodes for anything but tiny inputs, so this is purely a test reference.
from itertools import combinations
def remove_k_digits_slow(num, k):
keep = len(num) - k
best = min("".join(num[i] for i in pos) for pos in combinations(range(len(num)), keep))
return best.lstrip("0") or "0"The greedy rule
Think about one removal first. The leftmost digit of a number has the largest place value, so you want the earliest position to become as small as possible. Scan from the left for the first digit that is bigger than the digit after it, and delete it: the digit after it slides into that place and makes the number smaller there, while everything before it stays the same. If no such digit exists, the digits never go down, and deleting the last one is best. Repeating this one-removal step k times gives the optimal answer, and it is easy to code in O(n · k).
The stack removes the repeated rescans. Walk the digits from left to right and keep the digits you have decided to keep so far on a stack. Before pushing a new digit, look at the top: while removals remain and the top is bigger than the new digit, pop it, because that top is exactly a digit followed by a smaller one. Each pop is one removal. After the scan, the stack never goes down from bottom to top, so any removals still owed come off the end.
def remove_k_digits(num, k):
stack = []
for digit in num:
while k and stack and stack[-1] > digit:
stack.pop()
k -= 1
stack.append(digit)
if k:
stack = stack[:-k] # digits never fall now; drop from the end
return "".join(stack).lstrip("0") or "0"Comparing the characters directly works because the digit characters 0 to 9 sort in numeric order. The slice handles the leftover case, and the final expression handles both leading zeros and an empty result.
function removeKdigits(num, k) {
const stack = [];
for (const digit of num) {
while (k > 0 && stack.length && stack[stack.length - 1] > digit) {
stack.pop();
k--;
}
if (stack.length || digit !== "0") stack.push(digit); // no leading zeros
}
while (k > 0 && stack.length) {
stack.pop();
k--;
}
return stack.length ? stack.join("") : "0";
}The JavaScript version never pushes a zero onto an empty stack, so leading zeros cannot appear and no strip is needed later. Skipping that zero is not a removal, so k stays the same: in "30500" with k = 1, the 3 is popped by the first 0 (one removal), that 0 is skipped as a leading zero (free), and the result is "500". The trailing loop pops leftovers one at a time and stops if the stack runs out first.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Try every set of kept positions | O(C(n, k) · n) | O(n) per candidate |
| Remove the first falling digit, k times | O(n · k) | O(n) |
| Monotonic stack | O(n): each digit pushed and popped at most once | O(n) |
Inputs that catch bugs
- k equal to the length: the answer is "0".
- k of 0: the input comes back unchanged.
- Digits that never fall, like "1189": all removals happen at the end.
- A result that is all zeros, like "7000" with k = 1: return "0", not an empty string.
- Zeros in the middle that become leading zeros after a pop, like "30500".
- Long runs of the same digit: equal digits are not popped, because removing one gives the same prefix.
Common mistakes
- Converting the string to an integer, which overflows in many languages and drops information about length.
- Forgetting the leftover removals, so "1189" with k = 2 comes back unchanged.
- Returning an empty string instead of "0".
- Popping on greater than or equal, which wastes removals on equal digits.
- Writing the trim as stack[:-k] without checking k first. In Python, a slice ending at -0 is empty, so k = 0 would wipe the whole answer.
Variations
- Largest number after k removals: pop while the top is smaller than the incoming digit.
- Keep exactly m digits: the same as removing n - m.
- Smallest subsequence with every distinct letter once: a harder cousin that also needs each letter's last position, so you only pop a letter you know appears again later.
- Build the largest number of length m from two digit arrays: run this stack on each array for every split, then merge the two results greedily.
Explaining it to the interviewer
Fictional example
- Candidate
- The leftmost digits weigh the most, so I want the earliest position to be as small as possible.
- Candidate
- If some digit is bigger than the one after it, deleting it lets the smaller digit move up, and nothing before it changes. So the first such digit is the best single removal.
- Candidate
- Doing that k times works but rescans. A stack does it in one pass: pop while the top is bigger than the next digit and I still have removals.
- Interviewer
- What if you finish the scan with removals left?
- Candidate
- Then the stack never decreases, so the biggest digits are at the end and I cut from there. Then I strip leading zeros and return zero if it is empty.
Related problems
The stack here is the increasing twin of the one in Next Greater Element and Online Stock Span, where the stack falls instead. Asteroid Collision uses the same pop-then-push loop with a different rule for who survives. For a problem that keeps a running window rather than a stack, try Sliding Window Median.
Getting ready with Natively
Greedy answers sound convincing until someone asks why they are safe, so it is worth rehearsing that justification aloud. Natively, a desktop app for Mac and Windows, can read the problem from a screenshot in a practice run, suggest the stack and the three cleanup steps, and transcribe your reasoning. Afterwards you can check whether the leftover and leading-zero cases made it into your explanation. More on the LeetCode helper.
Questions people ask
How do you solve Remove K Digits?
Scan the digits left to right with a stack. While removals remain and the top digit is bigger than the incoming one, pop it. Push the digit. After the scan, remove any leftover count from the end, strip leading zeros, and return "0" if nothing is left.
Why does the greedy approach work for Remove K Digits?
The leftmost digits carry the most weight. Deleting the first digit that is followed by a smaller digit makes the earliest possible position smaller while leaving everything before it unchanged, so it is always the best single removal.
What is the time complexity of Remove K Digits?
O(n) with the stack, because each digit is pushed once and popped at most once. Repeating the one-removal scan k times would be O(n times k).
Why not convert the number to an integer?
The input can be far longer than any fixed-size integer type, and leading zeros in the result need handling as text anyway. Work on the string or a list of characters.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
