402. Remove K Digits

T: O(n)

S: O(n)

class Solution {
    public String removeKdigits(String num, int k) {
        int n = num.length();
        int remove = k;
        if (n == k) {
            return "0";
        }
        
        Deque<Integer> stack = new ArrayDeque<>();
        for (int i = 0; i < n; i++) {
            int number = Integer.valueOf(num.charAt(i) - '0');
            while (!stack.isEmpty() && number < stack.peek() && k != 0) {
                k--;
                stack.pop();
            }
            stack.push(number);
        }
        
        
        if (k != 0) {
            for (int i = 0; i < k; i++) {
                stack.pop();
            }
        }
        
        char[] result = new char[stack.size()];
        for (int i = stack.size()-1; i >= 0; i--) {
            result[i] = (char) (stack.pop() + '0');
        }

        StringBuilder sb = new StringBuilder(String.valueOf(result));
        while (sb.length() > 1 && sb.charAt(0) == '0') {
            sb.deleteCharAt(0);
        }
        
        return sb.toString();
    }
}

/*
remove larger one 
remain smaller in stack

number <= peek

1
2
1


0

1



1

*/ja

Last updated