Typorithm · medium

Remove K Digits

remove-k-digitsmonotonic-stackincreasing-stackgreedy-smallestcleanup
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Remove K Digits

0%

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'.

01

Pop larger digit before smaller.

02

Spend k on each pop.

03

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;
}

Read the implementation

Connect each part of the code to the concept before you type.

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) {

2. Spend a removal

Each pop uses one of the k allowed removals.

k -= 1

3. Trim remaining

If k removals remain, drop from the end (digits are increasing).

while (k > 0) {
    stack.pop();
    k -= 1;
  }

4. Strip leading zeros

Join the digits and remove any leading zeros.

stack.join("").replace(/^0+/, "")

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Remove K Digits: Lesson & Practice · Typorithm | ApplyDjinn