
Sponsored
Sponsored
This approach uses a stack to build the smallest possible number. We iterate over each digit in the string, and for each digit, we compare it with the top of the stack (if the stack is not empty). If the current digit is smaller than the top of the stack and we still have digits to remove, we pop from the stack. Finally, after the loop, if there are remaining digits to remove, we simply remove them from the end of the constructed stack. This ensures the smallest possible arrangement of the remaining digits.
Time Complexity: O(n), where n is the number of digits in num, because each digit is processed at most twice (once pushed and once popped).
Space Complexity: O(n), because of the space required for the stack to hold the digits.
1import java.util.Stack;
2
3public class Solution {
4 public String removeKdigits(String num, int k) {
5 Stack<Character> stack = new Stack<>();
6 for (char digit : num.toCharArray()) {
7 while (k > 0 && !stack.isEmpty() && stack.peek() > digit) {
8 stack.pop();
9 k--;
10 }
11 stack.push(digit);
12 }
13 StringBuilder result = new StringBuilder();
14 while (!stack.isEmpty()) {
15 result.append(stack.pop());
16 }
17 result.reverse();
18 while (result.length() > 1 && result.charAt(0) == '0') {
19 result.deleteCharAt(0);
20 }
21 return result.length() == 0 ? "0" : result.substring(0, result.length() - k);
22 }
23}This Java implementation utilizes the Stack to hold digits while processing them as per the given conditions. The result is constructed in reverse from the contents of the stack, and any extra digits post-loop are trimmed. Leading zeros are removed using a loop.