We can use Monotonic Increasing Order Stack. We will start from left, as we are biased towards MSD. We will continue to add the values to stack, till they are in increasing order.
If they are not in increasing order, we discard previous digits by popping and decrement k
Remove remaining k chars
For eg. for 12345 , we will add all elements in stack, and then pop out k elements.
Then we will just pop out k elements in total when we are done.
publicclassSolution {
public String removeKdigits(String num, int k) {
int len = num.length();
// Corner case: If k equals the length of num, return "0"if (k == len) {
return"0";
}
Deque<Character> stack =new ArrayDeque<>();
for (char ch : num.toCharArray()) {
// Whenever we find a digit smaller than the previous digit, discard the previous onewhile (k > 0 &&!stack.isEmpty() && stack.peekLast() > ch) {
stack.removeLast();
k--;
}
stack.addLast(ch);
}
// Remove remaining chars in case of cases like "1111" or "1234"while (k > 0) {
stack.removeLast();
k--;
}
// Construct the number from the Deque StringBuilder sb =new StringBuilder();
while (!stack.isEmpty()) {
sb.append(stack.removeFirst());
}
// Remove all zeros from the headwhile (sb.length() > 1 && sb.charAt(0) =='0') {
sb.deleteCharAt(0);
}
return sb.length() == 0 ?"0" : sb.toString();
}
}
classSolution:
defremoveKdigits(self, num: str, k: int) -> str:
length = len(num)
# Corner case: if k equals the length of num, return "0"if k == length:
return"0" stack = deque()
for ch in num:
# Whenever we find a digit which is smaller than the previous digit, discard the previous onewhile k >0and stack and stack[-1] > ch:
stack.pop()
k -=1 stack.append(ch)
# If k is still greater than 0, discard the remaining largest digitswhile k >0:
stack.pop()
k -=1# Construct the final number from the stack result =''.join(stack).lstrip('0') # Remove leading zerosreturn result if result else"0"