LeetCode #402 Medium

Remove K Digits

Remove K Digits is LeetCode 402 (Medium). Given a non-negative integer as the string num and an integer k, delete exactly k digits so the number left is as small as possible, and return it as a string.

  • The remaining digits keep their order.
  • Drop any leading zeros from the answer, and return "0" if nothing is left.
  • num can have 10⁵ digits, so it cannot be turned into a normal integer, and trying every set of deletions is out of the question.
Constraints
  • 1 <= k <= num.length <= 10⁵
  • num consists of only digits.
  • num does not have any leading zeros except for the zero itself.
monotonic-stackgreedystrings
Open on LeetCode ↗
02

Intuition

Every answer has the same length, n - k, so the smaller one is the one with the smaller digit at the first position where they differ. The leftmost digits matter most.

If a digit is bigger than the digit right after it, deleting it makes the number smaller. The digits before it stay, and its place is taken by a smaller digit. Doing this as far left as possible is always best.

A stack finds these digits in one pass. Before pushing a new digit, pop every larger digit on top while deletions remain. The stack then stays non-decreasing from bottom to top.

03

Approach

1

Scan the digits with a stack

For each digit d, while k > 0 and the top of the stack is larger than d, pop it and subtract 1 from k. Then push d. Each pop removes a digit that a smaller digit was about to follow.

2

Spend leftover deletions at the end

If k is still above 0, the stack is non-decreasing, so its largest digits are on top. Cut the last k digits; any other cut would move a bigger digit to the left.

3

Strip leading zeros

Remove zeros from the front of what is left. A pop can leave them at the front, and they add nothing to the value, so the answer is written without them.

4

Return "0" for an empty result

If every digit was deleted or every digit left was a zero, the string is empty. The smallest number is then zero, written "0".

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def removeKdigits(self, num: str, k: int) -> str:
▶3 stack = []
▶4 for d in num:
▶5 while k and stack and stack[-1] > d:
▶6 stack.pop()
▶7 k -= 1
▶8 stack.append(d)
▶9 del stack[len(stack) - k:]
▶10 return "".join(stack).lstrip("0") or "0"
num1432219stack1k left3 of 3stack is empty → push 1
digit1
stack1
k3
Nothing to compare with, so 1 goes on the stack.
num1432219stack14k left3 of 31 on top is not bigger than 4 → push 4
digit4
stack14
k3
Deleting 1 would let 4 move left, and 4 is not smaller, so that cannot help. Keep 1 and push 4.
num1432219stack14k left3 of 34 on top is bigger than 3 → delete 4
digit3
top4
k3 → 2
Putting 3 where 4 is makes the number smaller at that position, and the digits before it stay the same. A deletion is left, so 4 goes.
num1432219stack13k left2 of 31 on top is not bigger than 3 → push 3
digit3
stack13
k2
Deleting 1 would let 3 move left, and 3 is not smaller, so that cannot help. Keep 1 and push 3.
num1432219stack13k left2 of 33 on top is bigger than 2 → delete 3
digit2
top3
k2 → 1
Putting 2 where 3 is makes the number smaller at that position, and the digits before it stay the same. A deletion is left, so 3 goes.
num1432219stack12k left1 of 31 on top is not bigger than 2 → push 2
digit2
stack12
k1
Deleting 1 would let 2 move left, and 2 is not smaller, so that cannot help. Keep 1 and push 2.
num1432219stack122k left1 of 32 on top is not bigger than 2 → push 2
digit2
stack122
k1
Deleting 2 would let 2 move left, and 2 is not smaller, so that cannot help. Keep 2 and push 2.
num1432219stack122k left1 of 32 on top is bigger than 1 → delete 2
digit1
top2
k1 → 0
Putting 1 where 2 is makes the number smaller at that position, and the digits before it stay the same. A deletion is left, so 2 goes.
num1432219stack121k left0 of 3no deletions left → push 1 anyway
digit1
stack121
k0
2 is bigger than 1, but all 3 deletions are spent, so every remaining digit must stay.
num1432219stack1219k left0 of 31 on top is not bigger than 9 → push 9
digit9
stack1219
k0
Deleting 1 would let 9 move left, and 9 is not smaller, so that cannot help. Keep 1 and push 9.
num1432219answer1219k left0 of 3answer: 1219
result"1219"
Exactly 3 digits were deleted (the red ones). The smallest number left is 1219.
05

Common pitfalls

Forgetting deletions left after the scan

✗ Wrong
return "".join(stack).lstrip("0") or "0"
✓ Right
del stack[len(stack) - k:]
return "".join(stack).lstrip("0") or "0"

In a rising number like "12345" with k = 2, nothing is ever popped. Without the trim the answer is "12345" instead of "123".

Popping without checking k

✗ Wrong
while stack and stack[-1] > d:
    stack.pop()
    k -= 1
✓ Right
while k and stack and stack[-1] > d:
    stack.pop()
    k -= 1

The loop keeps popping after the budget is spent. "4321" with k = 1 pops all three larger digits and returns "1", but only one digit may go, so the answer is "321".

06

Edge cases

k equals the length, e.g. num = "9", k = 1

Every digit is deleted, the string is empty, and the answer is "0".

Zeros exposed after a pop, e.g. "10200", k = 1

Popping the 1 leaves "0200". Stripping gives "200", not "0200".

07

Complexity

Time
O(n)
Space
O(n)
Each digit is pushed once and popped at most once, so the inner loop does at most n pops in total. The stack holds up to n digits.
08

Remove K Digits FAQ

Is deleting one digit at a time, k times, also correct?

Yes. Each round scans for the first digit that is bigger than the one after it (or the last digit) and deletes it. That is the same greedy rule, but each round restarts from the left, so it costs O(n·k), up to about 10¹⁰ steps here.

How would I get the largest number instead?

Flip the comparison: pop while the top is smaller than the new digit. The stack then stays non-increasing, and leftover deletions still come off the end.

Which problems use the same stack idea?

Remove Duplicate Letters keeps a rising stack of letters, but it may only pop a letter that appears again later, instead of spending a budget of k deletions.