Problem: Remove K Digits

Given string num representing a non-negative integer `num`, and an integer
`k`, return the smallest possible integer after removing `k` digits from
`num`.


Python solution:
import math
import itertools
import bisect
import collections
import string
import heapq
import functools
import sortedcontainers
from typing import List, Dict, Tuple, Iterator

class Solution:
  def removeKdigits(self, num: str, k: int) -> str:
    if len(num) == k:
      return '0'

    ans = []
    stack = []

    for i, digit in enumerate(num):
      while k > 0 and stack and stack[-1] > digit:
        stack.pop()
        k -= 1
      stack.append(digit)

    for _ in range(k):
      stack.pop()

    for c in stack:
      if c == '0' and not ans:
        continue
      ans.append(c)

    return ''.join(ans) if ans else '0'


Java solution:
class Solution {
  public String removeKdigits(String num, int k) {
    if (num.length() == k)
      return "0";

    StringBuilder sb = new StringBuilder();
    LinkedList<Character> stack = new LinkedList<>();

    for (int i = 0; i < num.length(); ++i) {
      while (k > 0 && !stack.isEmpty() && stack.getLast() > num.charAt(i)) {
        stack.pollLast();
        --k;
      }
      stack.addLast(num.charAt(i));
    }

    while (k-- > 0)
      stack.pollLast();

    for (final char c : stack) {
      if (c == '0' && sb.length() == 0)
        continue;
      sb.append(c);
    }

    return sb.length() == 0 ? "0" : sb.toString();
  }
}


C++ solution:
class Solution {
 public:
  string removeKdigits(string num, int k) {
    if (num.length() == k)
      return "0";

    string ans;
    vector<char> stack;

    for (int i = 0; i < num.length(); ++i) {
      while (k > 0 && !stack.empty() && stack.back() > num[i]) {
        stack.pop_back();
        --k;
      }
      stack.push_back(num[i]);
    }

    while (k-- > 0)
      stack.pop_back();

    for (const char c : stack) {
      if (c == '0' && ans.empty())
        continue;
      ans += c;
    }

    return ans.empty() ? "0" : ans;
  }
};