> For the complete documentation index, see [llms.txt](https://jaywin.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jaywin.gitbook.io/leetcode/solutions/0402-remove-k-digits.md).

# 0402. Remove K Digits

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

## Description

Given string num representing a non-negative integer `num`, and an integer `k`, return *the smallest possible integer after removing* `k` *digits from* `num`.

**Example 1:**

```
**Input:** num = "1432219", k = 3
**Output:** "1219"
**Explanation:** Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.
```

**Example 2:**

```
**Input:** num = "10200", k = 1
**Output:** "200"
**Explanation:** Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.
```

**Example 3:**

```
**Input:** num = "10", k = 2
**Output:** "0"
**Explanation:** Remove all the digits from the number and it is left with nothing which is 0.
```

**Constraints:**

* `1 <= k <= num.length <= 105`
* `num` consists of only digits.
* `num` does not have any leading zeros except for the zero itself.

## ac: Monotoic queue

```java
class Solution {
    public String removeKdigits(String num, int k) {
        // Edge cases
        if (k == 0) return num;
        if (k == num.length()) return "0";
        if (k > num.length()) return null;
        
        char[] chars = num.toCharArray();
        Deque<Integer> stack = new ArrayDeque<>();
        
        for (int i = 0; i < chars.length; i++) {
            int val = chars[i] - '0';
            while (!stack.isEmpty() && stack.peek() > val && k > 0) {
                stack.pop();
                k--;
            }
            stack.push(val);
        }
        
        // We still need to remove more digit. stack is increasing, remove from the tail.
        while (k > 0) {
            stack.pop();
            k--;
        }
        
        StringBuilder sb = new StringBuilder();
        while (!stack.isEmpty()) {
            int curr = stack.pollLast();
            if (curr == 0 && sb.length() == 0) continue; // Skip leading 0
            sb.append(curr);
        }
        
        return sb.length() == 0 ? "0" : sb.toString();
    }
}

// O(N) time, O(N) space
```
