Remove K Digits

Remove k digits from a number so the digits left make the smallest possible number.

Given a string num that holds the digits of a non-negative integer, and an integer k no larger than the number of digits, remove exactly k digits so that the number left is as small as possible. The digits that stay keep their order. Return the result as a string without leading zeros, or "0" if no digits or only zeros are left.

Example 1
Input: num = "1432219", k = 3
Output: "1219"
Explanation: remove 4, 3 and the first 2.
Example 2
Input: num = "10200", k = 1
Output: "200"
Explanation: removing the 1 leaves "0200", which is written "200".
Example 3
Input: num = "10", k = 2
Output: "0"
Explanation: both digits are removed, and nothing left counts as 0.
Solution

The Idea

Picture the number 1432219 written on paper, and a pen to cross out three of its digits. The digits you keep close up, in the same order, and you want the number they make to be as small as possible. Crossing out 4, 3 and the first 2 leaves 1219, the answer to Example 1. But how would you find those three without trying every choice?

Every choice leaves a number with four digits. Between two numbers of the same length, the first place where their digits differ decides which is smaller: 1219 is smaller than 1229 because of the third digit. So the digits on the left matter most. We want the first digit as small as possible, then the second, and so on.

Read 1432219 from the left. The 1 is followed by 4, a bigger digit, so keeping the 1 is fine. The 4 is followed by 3, a smaller one. Crossing out the 4 moves the 3 into second place, and a number starting 13 beats one starting 14. So a digit should go when the digit right after it is smaller.

Once the 4 is gone, the 3 sits right after the 1 and is followed by 2, so the 3 should go as well. After each removal we look back at the digit we kept last. A stack fits this well: it is a pile where digits are added and removed only at the top, and here the top is the digit kept last.

Look at the picture below. Each row takes the next digit of 1432219. Before that digit is added, kept digits on top that are bigger than it are removed, as long as removals are left. The rightmost box in each row is the top of the stack.

Removing 3 digits from 1432219 with a stack. Each row shows the next digit, the digits removed before it is added, the kept digits on the stack, and the removals left. The 4, the 3 and the first 2 are removed, leaving 1219.

In the row whose next digit is 3, the 4 on top is bigger, so it appears under "removed", the 3 goes on the stack, and the removals left drop from 3 to 2. In the next row, the 2 removes the 3 the same way. The second 2 removes nothing, since it is not smaller than the 2 before it. Then the 1 removes that 2, which uses the last removal.

In the last row, the 9 joins the stack and the kept digits read 1219. One pass from left to right was enough: each new digit pushes out the bigger digits kept just before it, while removals remain. In the row whose next digit is 1, the kept digits 1, 2, 1 do not rise from left to right: that 1 removed one 2, but no removal was left for the other.

Solution Approach

Turning that idea into code means settling four things: which digits to remove instead of trying every choice, where to keep the digits that stay, what to do with removals left at the end, and how to write the result without leading zeros.

Choosing which digits to remove

Why not try every choice? To remove 3 of the 7 digits of 1432219 there are 35 choices, few enough to check one by one. With 100 digits and 50 to remove, there are about 1029, far too many.

The rule from the picture avoids that: find the first digit that is bigger than the digit after it, and remove it. Each digit before it is no bigger than its right neighbour, so removing one of those would put an equal or bigger digit in its place. Removing this one puts a smaller digit in its place, at the earliest position that can get smaller.

Applied on its own, the rule starts again from the left after every removal, so it can read the digits up to k times. The stack avoids going back: the digits it holds are already checked, and only the top can be the next one to go.

Keeping the digits on a stack

What should hold the kept digits? Anything that adds and removes at one end works. A StringBuilder does it well: append adds a digit at the end, deleteCharAt on the last position removes it, and the builder already holds the result as text.

While removals are left, the kept digits only go up or stay the same from bottom to top. A stack kept in one order like this is often called a monotonic stack.

Removals left at the end

What if the digits never go down? In 12345 no digit is bigger than the next, so the pass removes nothing and both removals of k = 2 are still left. The kept digits rise from left to right, so the biggest ones are at the end, and those are the ones to drop. 12345 becomes 123.

Leading zeros and an empty result

Can the kept digits start with 0? In Example 2 the 0 removes the 1, and the stack ends as 0200. That number is written 200, so zeros at the front are skipped. If every kept digit is 0, one 0 must stay. If no digits are kept at all, as in Example 3, the answer is "0".

Java Solution

The method removeKdigits works in these steps:

  1. First, create an empty StringBuilder named stack to hold the kept digits. Its last character is the top of the stack.
  2. Go through the digits of num with a for loop, one character d at a time. Inside, a while loop removes the top digit and lowers k by one, as long as k is above 0, the stack is not empty and the top is bigger than d. Then d is appended. Digit characters can be compared directly, because '0' to '9' come in order.
  3. After the for loop, drop the last k digits with stack.setLength(stack.length() - k). When every removal was used during the pass, k is 0 and nothing changes.
  4. Skip leading zeros: another while loop moves the position start forward over zeros, but stops one place before the end, so a lone 0 stays.
  5. Take stack.substring(start) as result, and return "0" if it is empty, or result otherwise.

The main method runs the three examples, then 12345 with removals left at the end, 100 where only zeros stay, 112 with equal digits side by side, and 54321 with no removals at all.

Java
public class RemoveKDigits {

    public static String removeKdigits(String num, int k) {
        StringBuilder stack = new StringBuilder(); // digits kept so far, used as a stack
        for (char d : num.toCharArray()) {
            while (k > 0 && stack.length() > 0 && stack.charAt(stack.length() - 1) > d) {
                stack.deleteCharAt(stack.length() - 1); // a bigger digit before a smaller one
                k--;
            }
            stack.append(d);
        }
        stack.setLength(stack.length() - k); // still removals left: drop from the end
        int start = 0;
        while (start < stack.length() - 1 && stack.charAt(start) == '0') {
            start++; // skip leading zeros, keeping at least one digit
        }
        String result = stack.substring(start);
        return result.isEmpty() ? "0" : result;
    }

    public static void main(String[] args) {
        System.out.println(removeKdigits("1432219", 3));
        System.out.println(removeKdigits("10200", 1));
        System.out.println(removeKdigits("10", 2));
        System.out.println(removeKdigits("12345", 2));
        System.out.println(removeKdigits("100", 1));
        System.out.println(removeKdigits("112", 1));
        System.out.println(removeKdigits("54321", 0));
    }
}

Running it prints:

Output
1219
200
0
123
0
11
54321

The answers 1219, 200 and 0 match the three examples. Look at 123 on the fourth line: nothing was removed during the pass over 12345, so setLength dropped the 4 and the 5 at the end. The 0 on the fifth line comes from 100. Its first 0 removed the 1, the stack held 00, and the skip loop stopped at the last 0.

The line 11 comes from 112. Equal digits do not remove each other, and the 2 is bigger than the 1 before it, so the pass removes nothing. The one removal is then spent at the end, on the 2. The last line shows that with k = 0, 54321 comes back unchanged, even though every digit is bigger than the next.

The original implementation, RemoveKDigits.java, is on GitHub.

Complexity

The work is one pass over the digits, plus the removals, and a digit can be removed only after it was added.

  • Time: O(n), for the n digits of num. Each digit is appended once and removed at most once, and deleteCharAt on the last character shifts nothing. Skipping the zeros and substring take one more pass.
  • Space: O(n), because stack can hold all n digits, as it does for 12345, and toCharArray() makes a copy of num.

A stack kept in one order is the monotonic stack pattern. Here k limits how many digits it may remove.