Remove K Digits
Medium
Topics
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
1219.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
Input: s = "10200", k = 1 Output: "200" Explanation: Removing the leading 1 exposes a 0, and leading zeros are stripped.
Example 3
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
- Keep a stack of the digits decided so far.
- 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. - Push the digit. Continue to the end of the string.
- If budget remains, drop that many digits from the end of the stack.
- 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"withk = 2never 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"import java.util.*;
class Solution {
public String removeKdigits(String s, int k) {
StringBuilder stack = new StringBuilder();
for (char digit : s.toCharArray()) {
while (k > 0 && stack.length() > 0 && stack.charAt(stack.length() - 1) > digit) {
stack.deleteCharAt(stack.length() - 1);
k--;
}
stack.append(digit);
}
if (k > 0) stack.setLength(Math.max(0, stack.length() - k));
int at = 0;
while (at < stack.length() && stack.charAt(at) == '0') at++;
String out = stack.substring(at);
return out.isEmpty() ? "0" : out;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: string removeKdigits(string s, int k) {
string stack;
for (char digit : s) {
while (k > 0 && !stack.empty() && stack.back() > digit) {
stack.pop_back();
k--;
}
stack += digit;
}
if (k > 0) stack.erase(stack.size() - min((size_t)k, stack.size()));
size_t at = stack.find_first_not_of('0');
if (at == string::npos) return "0";
return stack.substr(at);
}
};/**
* @param {string} s
* @param {number} k
* @return {string}
*/ var removeKdigits = function(s, k) {
const stack = [];
for (const digit of s) {
while (k > 0 && stack.length && stack[stack.length - 1] > digit) {
stack.pop();
k--;
}
stack.push(digit);
}
const kept = k > 0 ? stack.slice(0, stack.length - k) : stack;
const out = kept.join("").replace(/^0+/, "");
return out.length ? out : "0";
};