Remove K Digits
Remove k digits from a number so the digits left make the smallest possible number.
Given a string numkk"0"
Example 1
Output: "1219"
Explanation: remove 4, 3 and the first 2.
Example 2
Output: "200"
Explanation: removing the 1 leaves "0200", which is written "200".
Example 3
Output: "0"
Explanation: both digits are removed, and nothing left counts as 0.
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.
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
Keeping the digits on a stack
What should hold the kept digits? Anything that adds and removes at one end works. A StringBuilderappenddeleteCharAt
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
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
- First, create an empty
namedStringBuilder to hold the kept digits. Its last character is the top of the stack.stack - Go through the digits of
with anum loop, one characterfor at a time. Inside, ad loop removes the top digit and lowerswhile by one, as long ask is above 0, the stack is not empty and the top is bigger thank . Thend is appended. Digit characters can be compared directly, becaused to'0' come in order.'9' - After the
loop, drop the lastfor digits withk . When every removal was used during the pass,stack.setLength(stack.length() - k) is 0 and nothing changes.k - Skip leading zeros: another
loop moves the positionwhile forward over zeros, but stops one place before the end, so a lone 0 stays.start - Take
asstack.substring(start) , and returnresult if it is empty, or"0" otherwise.result
The main
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:
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
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
The original implementation,
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
. Each digit is appended once and removed at most once, andnum on the last character shifts nothing. Skipping the zeros anddeleteCharAt take one more pass.substring - Space: O(n), because
can hold all n digits, as it does for 12345, andstack makes a copy oftoCharArray() .num
A stack kept in one order is the k