Remove K Digits

medium

Given a non-negative integer as a string num and an integer k, remove exactly k digits so the remaining number is the smallest possible. Return it as a string (with no leading zeros; return "0" if everything is removed or the result is empty).

Hints

To make the number smallest, keep the most significant digits as small as possible.
When a smaller digit arrives, removing a larger digit to its left shrinks the number.
Use an increasing stack: pop larger digits (spending removals) before pushing.

Common doubts

A larger digit in a more significant position makes the number bigger. Replacing it with a smaller digit that comes right after reduces the value — the greedy local improvement.
The stack is non-decreasing, so the largest remaining digits sit at the end — drop the last k of them.
Popping can leave zeros at the front; strip them. If the string becomes empty, the answer is '0'.

Interview follow-ups

Flip the comparison: use a decreasing stack, popping smaller digits when a larger one arrives.
Track which indices are popped; the popped set (plus any trailing trim) are the removed digits.

Fun facts

  • This greedy is the string version of 'smallest subsequence' problems solved with a monotonic stack.
  • The same technique underlies 'Create Maximum Number' and 'Remove Duplicate Letters'.

Asked at

AmazonGoogleMicrosoft
Frequently Sometimes Occasionally
Example 1
Input: num = "1432219", k = 3
Output: 1219
Removing 4, 3, and 2 leaves the smallest number 1219.
Example 2
Input: num = "10200", k = 1
Output: 200
Remove the leading 1 to get 0200, then strip the leading zero -> 200.
Constraints

- 1 <= k <= num.length <= 10^5 - num consists of only digits - num has no leading zeros except '0' itself

Solve this problem →