1. Drop bigger leading digit
Remove a larger digit before a smaller one to shrink the number.
while (k > 0 && stack.length > 0 && stack[stack.length - 1] > digit) {Typorithm · medium
Step 1 of 8 · intro card
Monotonic Stack
Build an increasing stack, popping a larger digit before a smaller one while removals remain, then clean up.
To make the smallest number, remove a high digit whenever a smaller digit follows it.
An increasing-digit stack pops each larger top before pushing a smaller digit, spending one of k removals.
Leftover removals trim from the end, and a final cleanup strips leading zeros, defaulting to '0'.
Pop larger digit before smaller.
Spend k on each pop.
Trim leftovers, strip leading zeros.
function removeKdigits(num, k) {
const stack = [];
for (const digit of num) {
while (k > 0 && stack.length > 0 && stack[stack.length - 1] > digit) {
stack.pop();
k -= 1;
}
stack.push(digit);
}
while (k > 0) {
stack.pop();
k -= 1;
}
const result = stack.join("").replace(/^0+/, "");
return result === "" ? "0" : result;
}Connect each part of the code to the concept before you type.
Remove a larger digit before a smaller one to shrink the number.
while (k > 0 && stack.length > 0 && stack[stack.length - 1] > digit) {Each pop uses one of the k allowed removals.
k -= 1If k removals remain, drop from the end (digits are increasing).
while (k > 0) {
stack.pop();
k -= 1;
}Join the digits and remove any leading zeros.
stack.join("").replace(/^0+/, "")Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.