Remove K Digits - Problem
Given a string
The goal is to strategically remove digits to minimize the resulting number. For example, from "1432219" removing 3 digits, we want to get "1219" (not "4329" or "1432").
Key Points:
num representing a non-negative integer and an integer k, your task is to remove exactly k digits from the number to create the smallest possible integer.The goal is to strategically remove digits to minimize the resulting number. For example, from "1432219" removing 3 digits, we want to get "1219" (not "4329" or "1432").
Key Points:
- You must remove exactly
kdigits - The result should be the smallest possible number
- Leading zeros should be removed from the final result
- If all digits are removed, return "0"
Input & Output
example_1.py โ Basic Case
$
Input:
num = "1432219", k = 3
โบ
Output:
"1219"
๐ก Note:
Remove digits '4', '3', and '2' (the first '2') to get the smallest result. The optimal strategy is to remove larger digits that appear before smaller ones.
example_2.py โ All Same Digits
$
Input:
num = "10200", k = 1
โบ
Output:
"200"
๐ก Note:
Remove the leading '1' to get the smallest possible number. Since we want the smallest result, we remove the leftmost non-zero digit.
example_3.py โ Remove All Digits
$
Input:
num = "9", k = 1
โบ
Output:
"0"
๐ก Note:
When all digits are removed, return "0" as specified in the problem statement.
Visualization
Tap to expand
Understanding the Visualization
1
Scan Left to Right
Process each digit from left to right, as position matters for final value
2
Greedy Removal
When you see a smaller digit, remove any larger digits before it (while you have removals left)
3
Maintain Stack
Keep a stack of digits in non-decreasing order to build the optimal result
4
Handle Edge Cases
Remove from end if needed, clean leading zeros, return '0' if empty
Key Takeaway
๐ฏ Key Insight: The monotonic stack approach greedily removes larger digits when smaller ones appear later, ensuring we get the lexicographically smallest result in optimal O(n) time.
Time & Space Complexity
Time Complexity
O(n)
Single pass through the string, each element pushed and popped at most once
โ Linear Growth
Space Complexity
O(n)
Stack space for storing the result digits
โก Linearithmic Space
Constraints
- 1 โค num.length โค 104
- 0 โค k โค num.length
- num consists of only digits
- num does not have any leading zeros except for the zero itself
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code