




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.
1function removeKdigits(num, k) {
2    const stack = [];
3    for (let digit of num) {
4        while (k > 0 && stack.length && stack[stack.length - 1] > digit) {
5            stack.pop();
6            k--;
7        }
8        stack.push(digit);
9    }
10    stack.splice(stack.length - k, k);
11    while (stack.length && stack[0] === '0') {
12        stack.shift();
13    }
14    return stack.length ? stack.join('') : '0';
15}This JavaScript function simulates a stack using an array for its operations. During the traversal of num, it manages the stack to ensure the smallest number can be derived. It slices off any extra digits and removes any leading zeros using shift() on the resultant array.