Remove K Digits

Pattern: Monotonic stack

medium

Keep the digits on a stack. When the next digit is smaller than the top, removing the top makes the number smaller, so pop while you still may remove. Any removals left come off the end. Strip leading zeros; an empty result is 0.

The problem

Given a number as a string and k, remove exactly k digits so the result is as small as possible, and return it without leading zeros (or "0"). "1432219", k = 3 gives "1219"; "10200", k = 1 gives "200"; "10", k = 2 gives "0".

Think first

  • Which digit matters most for the size of a number?
  • When is removing a digit clearly good?
  • What if the digits never go down?

Hints

    Brute force, and why it fails

    Remove one digit at a time, trying every position each time: O(k × n²).

    The key insight

    Greedy with a stack: keep the kept digits increasing from left to right, popping a bigger digit whenever a smaller one comes and removals remain.

    Dry run

    stack1 4
    k3

    num = "1432219", k = 3. Push 1, push 4.

    Step 1 of 4

    The plan

    for c in num:
        while k > 0 and stack and top > c: pop; k -= 1
        push c
    remove k more from the end
    strip leading zeros; return "0" if empty
    

    Complexity

    Time
    O(n)
    Space
    O(n)

    Each digit is pushed and popped at most once.

    Edge cases

    • k equal to the length: "0".
    • Leading zeros after removals: "10200", k = 1 gives "200".
    • Increasing digits: remove from the end.
    I've built my logic, show the code

    Java

    class Solution {
        public String removeKdigits(String num, int k) {
            StringBuilder st = new StringBuilder();         // used as a stack of kept digits
            for (char c : num.toCharArray()) {
                while (k > 0 && st.length() > 0 && st.charAt(st.length() - 1) > c) {
                    st.deleteCharAt(st.length() - 1);       // a bigger digit before a smaller one: remove it
                    k--;
                }
                st.append(c);
            }
            st.setLength(st.length() - k);                  // still k to remove: take them off the end
            int start = 0;
            while (start < st.length() && st.charAt(start) == '0') start++;   // no leading zeros
            String out = st.substring(start);
            return out.isEmpty() ? "0" : out;
        }
    }

    C++

    class Solution {
    public:
        string removeKdigits(string num, int k) {
            string st;                                      // used as a stack of kept digits
            for (char c : num) {
                while (k > 0 && !st.empty() && st.back() > c) {
                    st.pop_back();                          // a bigger digit before a smaller one: remove it
                    k--;
                }
                st.push_back(c);
            }
            st.resize(st.size() - k);                       // still k to remove: take them off the end
            size_t start = 0;
            while (start < st.size() && st[start] == '0') start++;   // no leading zeros
            string out = st.substr(start);
            return out.empty() ? "0" : out;
        }
    };

    Python

    class Solution:
        def removeKdigits(self, num: str, k: int) -> str:
            st = []                                 # a stack of kept digits
            for c in num:
                while k and st and st[-1] > c:
                    st.pop()                        # a bigger digit before a smaller one: remove it
                    k -= 1
                st.append(c)
            if k:
                st = st[:-k]                        # still k to remove: take them off the end
            return "".join(st).lstrip("0") or "0"   # no leading zeros

    Common mistakes

    • Forgetting to remove leftover k at the end.
    • Returning an empty string instead of "0".

    Similar problems