Remove K Digits (LeetCode 402): Solution and Explanation

Medium
String
Stack
Greedy
Monotonic Stack

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.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

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

  1. Create an empty list stack to hold the digits being kept.
  2. For each digit, while k > 0, the stack is not empty, and stack[-1] > digit, pop the stack and decrease k.
  3. Push the current digit onto the stack.
  4. After the scan, drop any remaining deletions from the end with stack[:len(stack) - k].
  5. Join the digits, strip leading zeros with lstrip('0'), and return 0 if the result is empty.

Step-by-step example

num = 1432219, k = 3
  1. Push 1, then push 4. The stack is [1,4] and k is still 3.
  2. Digit 3 is smaller than 4, so pop 4 and k becomes 2. Push 3, giving [1,3].
  3. Digit 2 is smaller than 3, so pop 3 and k becomes 1. Push 2, giving [1,2].
  4. The next digit 2 is not smaller than the top 2, so just push it, giving [1,2,2].
  5. Digit 1 is smaller than 2, so pop once and k becomes 0. Push 1, giving [1,2,1].
  6. 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'

Time and space complexity

Time

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.

Space

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 = 2 nothing is ever popped, and you must still remove the last two digits to get 123.
  • Returning an empty string instead of 0. For num = 10, k = 1 the stack ends as [0], and stripping leading zeros leaves nothing, so you need the or '0' fallback. The same applies when k equals 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 if instead of a while for 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.