Remove K Digits

Remove k digits from a number-string to make the smallest result — monotonic increasing stack.

Medium
Time O(n) Space O(n)
LeetCode
3 min read
greedy monotonic-stack string

Problem#

Remove exactly k digits from num to produce the smallest possible number (as a string, no leading zeros).

Examples#

  • num = "1432219", k = 3"1219"
  • num = "10200", k = 1"200"

Constraints#

  • 1 <= num.length <= 10^5.

Approach#

Monotonic increasing stack. For each digit, pop the top while top > digit and we still have removals (k > 0). Push the digit. After the loop, pop remaining k from the end. Strip leading zeros.

Solution#

Remove K Digits
class Solution {
public:
string removeKdigits(string num, int k) {
string st;
for (char c : num) {
while (!st.empty() && st.back() > c && k > 0) {
st.pop_back(); --k;
}
st.push_back(c);
}
while (k-- > 0 && !st.empty()) st.pop_back();
int start = 0;
while (start < (int)st.size() && st[start] == '0') ++start;
string ans = st.substr(start);
return ans.empty() ? "0" : ans;
}
};

Editorial#

Removing a “peak” digit (a digit larger than its right neighbor) is locally best — it lowers the digit at a high-significance position. The monotonic-stack enforces “non-decreasing from left to right” within the kept digits, which is the smallest possible.

Complexity#

  • Time: O(n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.