Remove K Digits (LeetCode 402): Solution and Explanation
You get a non-negative integer written as a string and a count k. Delete exactly k of its digits, keeping the rest in their original order, so that the number left over is as small as possible.
Watch it run step by step
Try your own input and write the code →Intuition
Brute force would try every way to choose k digits to delete, which is a combinatorial explosion. Even a smarter greedy that scans the string again for each of the k deletions costs O(n × k). The key is to notice what makes one number smaller than another of the same length: the leftmost position where they differ decides everything.
So you want the leftmost digits to be as small as possible. Scan from the left, and whenever a digit is larger than the digit that follows it, deleting it pulls a smaller digit one position to the left, which shrinks the number. Deleting a digit that is smaller than or equal to its successor never helps at that position.
A stack makes this efficient. Keep the digits you have decided to keep on a stack. When a new digit arrives and the top of the stack is larger, pop the top and spend one deletion, and keep popping while that is still true and you have deletions left. Then push the new digit. The stack stays non-decreasing from bottom to top, which is why this is called a monotonic stack.
Two cleanup steps finish the job. If you run out of input with deletions left over, the stack is already non-decreasing, so the best digits to remove are the largest ones at the end. Finally, strip leading zeros, and if nothing is left, the answer is 0.
Approach: Greedy monotonic stack
- Create an empty list
stackto hold the digits being kept. - For each digit, while
k > 0, the stack is not empty, andstack[-1] > digit, pop the stack and decreasek. - Push the current digit onto the stack.
- After the scan, drop any remaining deletions from the end with
stack[:len(stack) - k]. - Join the digits, strip leading zeros with
lstrip('0'), and return0if the result is empty.
Step-by-step example
num = 1432219, k = 3
- Push 1, then push 4. The stack is [1,4] and k is still 3.
- Digit 3 is smaller than 4, so pop 4 and k becomes 2. Push 3, giving [1,3].
- Digit 2 is smaller than 3, so pop 3 and k becomes 1. Push 2, giving [1,2].
- The next digit 2 is not smaller than the top 2, so just push it, giving [1,2,2].
- Digit 1 is smaller than 2, so pop once and k becomes 0. Push 1, giving [1,2,1].
- With k at 0, digit 9 is pushed, giving [1,2,1,9]. Nothing is trimmed and there are no leading zeros, so the answer is 1219.
Code: Python, Java, C++
1class Solution:
2 def removeKdigits(self, num: str, k: int) -> str:
3 stack = []
4 for digit in num:
5 while k > 0 and stack and stack[-1] > digit:
6 stack.pop()
7 k -= 1
8 stack.append(digit)
9 # Remove remaining k digits from end
10 stack = stack[:len(stack) - k]
11 # Remove leading zeros and return
12 return ''.join(stack).lstrip('0') or '0'1class Solution {
2 public String removeKdigits(String num, int k) {
3 StringBuilder stack = new StringBuilder();
4 for (char digit : num.toCharArray()) {
5 while (k > 0 && stack.length() > 0 && stack.charAt(stack.length() - 1) > digit) {
6 stack.deleteCharAt(stack.length() - 1);
7 k--;
8 }
9 stack.append(digit);
10 }
11 // Remove remaining k digits from end
12 while (k > 0 && stack.length() > 0) {
13 stack.deleteCharAt(stack.length() - 1);
14 k--;
15 }
16 // Remove leading zeros
17 while (stack.length() > 0 && stack.charAt(0) == '0') {
18 stack.deleteCharAt(0);
19 }
20 return stack.length() == 0 ? "0" : stack.toString();
21 }
22}1class Solution {
2public:
3 string removeKdigits(string num, int k) {
4 string stack;
5 for (char digit : num) {
6 while (k > 0 && !stack.empty() && stack.back() > digit) {
7 stack.pop_back();
8 k--;
9 }
10 stack.push_back(digit);
11 }
12 // Remove remaining k digits from end
13 while (k > 0 && !stack.empty()) {
14 stack.pop_back();
15 k--;
16 }
17 // Remove leading zeros
18 size_t start = stack.find_first_not_of('0');
19 if (start == string::npos) return "0";
20 return stack.substr(start);
21 }
22};Time and space complexity
O(n)
Each digit is pushed once and popped at most once, so the inner while loop does O(n) work across the whole scan. Slicing, joining and stripping are each linear.
O(n)
The stack can hold every digit, for example when the input is already non-decreasing, and the output string is built from it.
Other approaches
Repeated greedy scans (time O(n × k), space O(n))
Do k rounds, and in each round find the first position where a digit is greater than the next one and delete it, or delete the last digit if there is none. It applies the same greedy rule without a stack, but each round rescans the string.
Common mistakes
- Forgetting the trailing trim. For
num = 12345, k = 2nothing is ever popped, and you must still remove the last two digits to get 123. - Returning an empty string instead of
0. Fornum = 10, k = 1the stack ends as [0], and stripping leading zeros leaves nothing, so you need theor '0'fallback. The same applies whenkequals the length of the number. - Stripping leading zeros before the stack logic. Zeros at the front are cheap to keep and the greedy needs them in place to count positions correctly.
- Using an
ifinstead of awhilefor the pops. One new small digit can justify removing several larger digits before it.
Frequently asked questions
Why does removing a digit that is larger than the next one work?
The leftmost differing digit decides which of two equal-length numbers is smaller. Removing a digit that is bigger than its successor puts a smaller digit in that spot, and no other single deletion can make that position smaller.
What is a monotonic stack in Remove K Digits?
It is a stack whose values never decrease from bottom to top. Each new digit pops larger digits off the top while deletions remain, so the kept prefix is always the smallest it can be.
Why is the time complexity O(n) when there is a nested loop?
Every digit enters the stack once and can leave it at most once. The total number of pops over the whole run is bounded by n, so the nested loop is amortized linear.