Remove K Digits - Problem

Given a string num representing a non-negative integer and an integer k, return the smallest possible integer after removing k digits from num.

The result should not have leading zeros, except when the result is "0".

Example: If num = "1432219" and k = 3, we can remove digits to get "1219" by removing "4", "3", and "2".

Input & Output

Example 1 — Basic Removal
$ Input: num = "1432219", k = 3
Output: "1219"
💡 Note: Remove digits 4, 3, and 2 (first occurrence) to get the smallest result. The greedy approach removes larger digits when encountered: 4>3 so remove 4, then 3>2 so remove 3, then 2>2 so remove the first 2.
Example 2 — Leading Zero Handling
$ Input: num = "10200", k = 1
Output: "200"
💡 Note: Remove the first digit '1' to get '0200', then remove leading zeros to get '200'. This shows the importance of handling leading zeros in the result.
Example 3 — Remove All Same Digits
$ Input: num = "10", k = 2
Output: "0"
💡 Note: When we need to remove all digits (k >= length), the result should be '0'. This is a special edge case.

Constraints

  • 1 ≤ k ≤ num.length ≤ 105
  • num consists of only digits
  • num does not have leading zeros except for num = "0"

Visualization

Tap to expand
Remove K Digits - Greedy with Monotonic Stack INPUT num = "1432219" 1 4 3 2 2 1 9 0 1 2 3 4 5 6 k = 3 Monotonic Stack Structure: Stack (bottom to top) keeps increasing digits [ ... ] ALGORITHM STEPS 1 Initialize Stack Empty stack, traverse digits 2 Compare and Pop If curr < top, pop (k times) 3 Push Current Digit Add digit to stack 4 Build Result Remove leading zeros Stack Trace: Digit Stack k Action 1 [1] 3 push 4 [1,4] 3 push 3 [1,3] 2 pop 4 2 [1,2] 1 pop 3 2 [1,2,2] 1 push 1 [1,2,1] 0 pop 2 9 [1,2,1,9] 0 push FINAL RESULT Digits Removed (k=3): 1 4 3 2 2 1 9 Final Stack Content: 1 2 1 9 OUTPUT "1219" OK - Smallest! Time: O(n) | Space: O(n) Key Insight: The greedy strategy works because removing a larger digit that comes before a smaller digit always produces a smaller number. The monotonic stack maintains digits in increasing order, ensuring we always remove the first "peak" digit (where digit[i] > digit[i+1]) to minimize the result. TutorialsPoint - Remove K Digits | Greedy with Monotonic Stack Approach
Asked in
Google 35 Amazon 28 Facebook 22 Apple 18
125.0K Views
High Frequency
~25 min Avg. Time
3.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen