You are given a string num holding the digits of a non-negative whole number, and an integer k. Delete exactly k digits from it; the digits that stay keep their order.
Return the smallest number you can end up with, as a string with no leading zeros. If nothing is left, or only zeros are left, return "0".
Example 1
Input: num = "52814", k = 2 Output: "214" Why: delete the 5 and the 8
2 more examples and the constraints
Example 2
Input: num = "70400", k = 1 Output: "400" Why: deleting the 7 leaves 0400, which is 400
Example 3
Input: num = "35", k = 2 Output: "0" Why: every digit is gone
Constraints
- 1 ≤ k ≤ length of num ≤ 100,000
- num holds only the digits 0 to 9
- num has no leading zeros, unless it is "0" itself
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Remove one, rescanO(n·k)
- Monotonic stackO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100,000 digits, k = 50,000 | Verdict |
|---|---|---|---|
| Remove one, rescan | O(n·k) | Explains the greedy; too slow | |
| Monotonic stack | O(n) | Best; one pass |
n = number of digits, k = digits to delete.
Edge cases to test
- k equals the length. Everything is deleted: return "0", not an empty string.
- Leading zeros appear. "70400" with k = 1 leaves "0400": strip it to "400".
- Digits only rise. "12345" with k = 2 never pops; cut the last two to get "123".
- Only zeros remain. "100" with k = 1 leaves "00", which is "0".
- Equal digits. "112" with k = 1: equal digits are not a fall, so the 2 goes, giving "11".
Common mistakes
- Forgetting the leftover k when the digits never fall, so fewer than k digits are removed.
- Returning an empty string instead of "0".
- Popping on equal digits too, or stripping zeros before the scan ends.
How to talk through it
- 1Clarify. Do the kept digits stay in order? What should come back when everything is deleted?
- 2Find the greedy rule. The leftmost digit matters most, so delete the first digit that is bigger than the next one.
- 3Give the simple version. Apply that rule k times with a rescan; O(n·k).
- 4Code the stack. Pop bigger digits while k lasts, then trim the end and strip zeros.
- 5Test out loud. Run "35" with k = 2, "70400" with k = 1 and "12345" with k = 2.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?