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: Create Smallest NumberInput String1432219"1432219", k = 3Remove Strategy❌ Remove larger digits✓ Keep smaller digitsGreedy Process: Remove 4, 3, 2Result String1219Output: "1219"
Understanding the Visualization
1
Input
String num and integer k representing digits to remove
2
Process
Greedily remove larger digits to minimize result
3
Output
Smallest possible number after removing k digits
Key Takeaway
🎯 Key Insight: Always remove the first digit that's larger than the next digit to minimize the result
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