import java.util.Stack;
class Solution {
public String removeKdigits(String n, int k) {
Stack<Character> st = new Stack<>();
for (int i = 0; i < n.length(); i++) {
char c = n.charAt(i);
while (k > 0 && !st.isEmpty() && st.peek() > c) {
st.pop();
k--;
}
st.push(c);
}
while (k > 0 && !st.isEmpty()) {
st.pop();
k--;
}
String res = "";
for (char c : st) res += c;
int idx = 0;
while (idx < res.length() && res.charAt(idx) == '0') idx++;
res = idx == res.length() ? "0" : res.substring(idx);
return res;
}
}