Online store~25 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-402monotonic-stack · stacks
An online store runs a lucky draw. Every order has a receipt number made of digits. A winner may strike out exactly k digits from their number. The digits that remain keep their order and form a new number, and the smallest new number wins the biggest prize.
Leading zeros do not count, so 007 counts as 7. If every digit is struck out, the new number is 0. A receipt number can have up to 100,000 digits.
Write smallest_after_removing(number, k).
number is a string of the digits 0 to 9. It may start with zeros.k digits from number. The digits that remain keep their order."0" if nothing remains or only zeros remain.Input: number = "5927384", k = 3
Output: "2384"Read the digits left to right and keep them on a stack. When a digit is smaller than the one on top, and removals remain, the top is larger and sits earlier, so remove it.
| Digit read | Digits popped | Removals left | Stack after |
|---|---|---|---|
| 5 | none | 3 | 5 |
| 9 | none | 3 | 5, 9 |
| 2 | 9, then 5 | 1 | 2 |
| 7 | none | 1 | 2, 7 |
| 3 | 7 | 0 | 2, 3 |
| 8 | none | 0 | 2, 3, 8 |
| 4 | none | 0 | 2, 3, 8, 4 |
No removals are left at the end, so the number is the stack read from bottom to top: 2384.
Input: number = "30500", k = 1
Output: "500"Striking out the 3 leaves 0500. Leading zeros are dropped, so the number is 500.
Input: number = "73", k = 2
Output: "0"Both digits are struck out, so nothing remains. The number is 0.
1 ≤ length of number ≤ 10^5, made of the digits 0 to 90 ≤ k ≤ length of numberA plan that scans the whole number for every removal costs up to n × k steps: close to 4 × 10^9 when k is half of 100,000. That is too slow.
So the work must be close to n steps in all. Each digit should be handled a constant number of times, even though a removal can reach far back.