Skip to content

Latest commit

 

History

History
58 lines (42 loc) · 986 Bytes

File metadata and controls

58 lines (42 loc) · 986 Bytes

Remove K Digits

Problem Link

https://leetcode.com/problems/remove-k-digits/


Pattern

  • Stack
  • Greedy

Approach

Use a monotonic increasing stack and remove larger digits while k remains.


Time Complexity

O(n)

Space Complexity

O(n)


Java Solution

import java.util.*;
class Solution {
    public String removeKdigits(String num, int k) {
        Stack<Character> stack = new Stack<>();
        for (char c : num.toCharArray()) {
            while (k > 0 && !stack.isEmpty() && stack.peek() > c) {
                stack.pop();
                k--;
            }
            stack.push(c);
        }
        while (k > 0 && !stack.isEmpty()) {
            stack.pop();
            k--;
        }
        StringBuilder ans = new StringBuilder();
        for (char c : stack) {
            if (ans.length() == 0 && c == '0') continue;
            ans.append(c);
        }
        return ans.length() == 0 ? "0" : ans.toString();
    }
}