The 30 second answer
To make the smallest possible number after deleting k digits, I want earlier digits to be as small as possible. I build an increasing stack of digits and, while the new digit is smaller than the top and I still have deletions left, I pop the top. I then drop any leftover deletions from the end, strip leading zeros, and return "0" if nothing remains.
Problem Given a non-negative integer num as a string and an integer k, remove k digits from num so that the remaining number, returned as a string without leading zeros, is the smallest possible. If every digit is removed, return "0". Original: LeetCode 402: Remove K Digits.
Understanding the prompt You may not reorder digits, only delete k of them and keep the relative order of the rest. Leading zeros in the result must be stripped, except that a result of zero is the string "0". A non-increasing number, such as "32" with k = 1, should drop the last digit, not the first, unless a later smaller digit appears.
Pattern recognition A monotonic increasing stack, used as a greedy choice: a descent is a place where deleting the previous larger digit makes the number smaller.
Brute force Enumerate every way to keep n โ k digits in order and take the minimum: combinatorial.
Optimal Walk the digits left to right. While k > 0 and the stack is non-empty and the top is greater than the current digit, pop and decrement k: that descent is a profitable deletion. Then push the current digit. If k is still positive at the end, pop k trailing (largest-suffix) digits. Build the string from the bottom of the stack, strip leading zeros, and return "0" if the result is empty.
Alternatives The same greedy idea can be written with a StringBuilder as the stack. A priority queue does not respect digit order, so it is the wrong tool.
Java solution
import java.util.ArrayDeque;
public class RemoveKDigits {
static String removeKdigits(String num, int k) {
var st = new ArrayDeque<Character>();
for (int i = 0; i < num.length(); i++) {
char c = num.charAt(i);
while (k > 0 && !st.isEmpty() && st.peek() > c) {
st.pop();
k--;
}
st.push(c);
}
while (k > 0 && !st.isEmpty()) {
st.pop();
k--;
}
var sb = new StringBuilder();
while (!st.isEmpty()) sb.append(st.removeLast()); // bottom to top
int i = 0;
while (i < sb.length() && sb.charAt(i) == '0') i++;
var ans = sb.substring(i);
return ans.isEmpty() ? "0" : ans;
}
public static void main(String[] args) {
System.out.println(removeKdigits("1432219", 3)); // 1219
System.out.println(removeKdigits("10200", 1)); // 200
System.out.println(removeKdigits("10", 2)); // 0
}
}Complexity O(n) time, each digit pushed and popped at most once. O(n) extra space.
Edge cases
- Official samples: "1432219" with k = 3 returns "1219"; "10200" with k = 1 returns "200" after stripping a leading zero; "10" with k = 2 returns "0".
- An already increasing number: deletions come from the end.
Follow-ups
- Remove duplicate letters to get the smallest subsequence is a close relative, with an extra 'must keep one of each letter' constraint.
- Daily Temperatures is the same family of monotonic stack, asking a different question of the structure.
Tests "1432219" with k=3 returns "1219". "10200" with k=1 returns "200". "10" with k=2 returns "0".
How to say it in the interview "I want the leftover digits to form the smallest number, so I keep an increasing stack. Whenever the new digit is smaller than the top and I still have deletions left, I drop the top. I use any leftover deletions on the end, strip leading zeros, and return "0" if nothing is left."
Sources (3)
- LeetCode 402: Remove K Digitsleetcode.com
- Java SE 17 API: ArrayDequedocs.oracle.com
- Java SE 17 API: StringBuilderdocs.oracle.com