Remove K Digits

medium string stack greedy monotonic stack

Problem

Given a non-negative integer represented as a string num and an integer k, remove k digits to form the smallest possible number (also a string). Strip any leading zeros and return "0" if everything is removed.

Inputnum = "1432219", k = 3
Output"1219"
Each "drop" pops a digit from the stack whenever the next digit is smaller — making the result more left-heavy with small digits.

def remove_k_digits(num, k):
    stack = []
    for c in num:
        while k > 0 and stack and stack[-1] > c:
            stack.pop(); k -= 1
        stack.append(c)
    while k > 0: stack.pop(); k -= 1
    res = ''.join(stack).lstrip('0')
    return res or '0'
function removeKdigits(num, k) {
  const stack = [];
  for (const c of num) {
    while (k > 0 && stack.length && stack[stack.length - 1] > c) {
      stack.pop(); k--;
    }
    stack.push(c);
  }
  while (k--) stack.pop();
  const res = stack.join('').replace(/^0+/, '');
  return res || '0';
}
class Solution {
    public String removeKdigits(String num, int k) {
        Deque<Character> stack = new ArrayDeque<>();
        for (char c : num.toCharArray()) {
            while (k > 0 && !stack.isEmpty() && stack.peek() > c) {
                stack.pop(); k--;
            }
            stack.push(c);
        }
        while (k-- > 0 && !stack.isEmpty()) stack.pop();
        StringBuilder sb = new StringBuilder();
        for (Iterator<Character> it = stack.descendingIterator(); it.hasNext(); ) sb.append(it.next());
        int i = 0; while (i < sb.length() && sb.charAt(i) == '0') i++;
        String r = sb.substring(i);
        return r.isEmpty() ? "0" : r;
    }
}
string removeKdigits(string num, int k) {
    string st;
    for (char c : num) {
        while (k > 0 && !st.empty() && st.back() > c) { st.pop_back(); k--; }
        st.push_back(c);
    }
    while (k-- > 0 && !st.empty()) st.pop_back();
    int i = 0; while (i < (int)st.size() && st[i] == '0') i++;
    string r = st.substr(i);
    return r.empty() ? "0" : r;
}
Time: O(n) Space: O(n)