Algo-Sim › Stacks & Monotonic Stack

Remove K Digits

Medium · Stacks & Monotonic Stack · step through it in Java, Python and C++ on your own input

Keep an increasing stack of digits: pop a larger digit while removals are left, drop leading zeros, and trim the tail.

Problem

The string num is a non-negative integer and k is how many of its digits to remove. Return the smallest possible number, as a string, after removing exactly k digits. The result has no leading zeros, and is "0" if nothing is left.

Constraints

Edge cases to test

Follow-up questions

Why is removing the first descent greedy-optimal?
A smaller digit earlier always makes a smaller number, so popping a larger digit before it is never worse.
What about the largest number instead?
Keep a decreasing stack instead, removing a smaller digit before a larger one.

Solution

Java

public String removeKdigits(String num, int k) {
    StringBuilder stack = new StringBuilder();
    for (char d : num.toCharArray()) {
        while (k > 0 && stack.length() > 0 && stack.charAt(stack.length() - 1) > d) {
            stack.deleteCharAt(stack.length() - 1);
            k--;
        }
        if (stack.length() > 0 || d != '0') stack.append(d);
    }
    stack.setLength(Math.max(0, stack.length() - k));
    return stack.length() == 0 ? "0" : stack.toString();
}

Python

def remove_kdigits(num, k):
    stack = []
    for d in num:
        while k > 0 and stack and stack[-1] > d:
            stack.pop()
            k -= 1
        if stack or d != '0': stack.append(d)
    del stack[max(0, len(stack) - k):]
    return ''.join(stack) or '0'

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    string removeKdigits(string num, int k) {
        string stack = "";
        for (char d : num) {
            while (k > 0 && !stack.empty() && stack.back() > d) {
                stack.pop_back();
                k--;
            }
            if (!stack.empty() || d != '0') stack.push_back(d);
        }
        stack.resize(max(0, (int)stack.size() - k));
        return stack.empty() ? "0" : stack;
    }
};

More Stacks & Monotonic Stack problems