Remove K Digits

Medium

Topics
StringStackGreedyMonotonic Stack

Given a string s of digits representing a non-negative integer, remove exactly k digits so that the remaining digits, in their original order, form the smallest possible number.

Return that number as a string, with no leading zeros. If every digit is removed, return "0".

Example 1

s10413223241596
answer1219
keptone of the 3 removed
Exactly 3 digits must go, and the kept digits stay in their original order, so the result has a fixed length and is judged from its leftmost digit onwards — which is why an early large digit costs far more than a late one. The answer is 1219.
One cell per digit; the small numbers underneath are indices.
Input:  s = "1432219", k = 3
Output: "1219"
Explanation: Removing 4, 3 and the second 2 leaves 1219, and nothing smaller is reachable in three removals.

Example 2

s1001220304
answer200
keptone of the 1 removed
Note the removal exposed a leading zero, which is dropped.
Input:  s = "10200", k = 1
Output: "200"
Explanation: Removing the leading 1 exposes a 0, and leading zeros are stripped.

Example 3

s1001
answer0
one of the 2 removed
Input:  s = "10", k = 2
Output: "0"
Explanation: Nothing is left, and the answer for an empty result is the single digit 0.

Constraints

  • 1 <= s.length <= 10^5
  • 0 <= k <= s.length
  • s consists of digits only and has no leading zero unless it is "0"
Editorial — intuition, approach, complexity and pitfalls

Intuition

Length is fixed once k is fixed, so the comparison between two candidate answers is decided by the leftmost digit where they differ. That makes the earliest digits enormously more important than the later ones, and it tells you what to delete: any digit that is larger than the digit right after it.

Why that is the right rule: if s[i] > s[i+1] then deleting s[i] pulls a smaller digit into position i, which improves the number at the most significant place that can still change. Keeping s[i] and deleting something later can never recover from that.

Applied repeatedly, this says the kept digits should be non-decreasing as far as the budget allows — which is exactly a stack that pops while its top exceeds the incoming digit. If the budget runs out the rest of the string is kept as is; if digits run out with budget left, the remaining removals come off the end, because by then the kept digits are already non-decreasing and the largest are last.

Approach

  1. Keep a stack of the digits decided so far.
  2. For each digit of s: while the budget is non-zero and the top of the stack is larger than this digit, pop and spend one removal.
  3. Push the digit. Continue to the end of the string.
  4. If budget remains, drop that many digits from the end of the stack.
  5. Strip leading zeros from the result, and return "0" if nothing is left.

Walkthrough

s = "1432219", k = 3

digit  budget  pops                 stack
  1      3     --                   1
  4      3     --                   14
  3      3     4 > 3, pop (k=2)     13
  2      2     3 > 2, pop (k=1)     12
  2      1     2 is not > 2         122
  1      1     2 > 1, pop (k=0)     121
  9      0     budget spent         1219

no budget left, no leading zeros  ->  "1219"

---

s = "10200", k = 1
  1 pushed; 0 arrives and 1 > 0, so pop (k=0)
  rest kept as is  ->  "0200"
  strip leading zeros  ->  "200"

Complexity

  • Time — O(n): each digit is pushed once and popped at most once.
  • Space — O(n): the stack.

Common Pitfalls

  • Forgetting the leftover budget. "12345" with k = 2 never pops anything, and the answer is "123" — taken off the end.
  • Stripping leading zeros before the removals rather than after. The zeros that matter are the ones exposed by a removal, as in example 2.
  • Returning an empty string. When everything is removed the answer is "0".
  • Popping on equality. Removing a digit equal to the next one costs budget and changes nothing, which wastes a removal that could have helped later.
  • Deleting the k largest digits. That ignores position, and position is the whole problem — a 9 at the end is harmless, a 9 at the front is not.

Full Solution — all languages

class Solution:
    def removeKdigits(self, s, k):
        stack = []
        for digit in s:
            while k and stack and stack[-1] > digit:
                stack.pop()
                k -= 1
            stack.append(digit)
        if k:
            stack = stack[:-k]
        return "".join(stack).lstrip("0") or "0"
SensAI
Beta
Tap the mic to stop voice mode