Introduction
The "Remove K Digits" problem is a classic greedy algorithm and monotonic stack interview question. Given a number represented as a string and an integer k, the goal is to remove exactly k digits so that the resulting number is as small as possible.
The relative order of the remaining digits must remain unchanged. Additionally, the final result should not contain leading zeros, and if all digits are removed, the function should return "0".
This problem demonstrates how a greedy strategy combined with a stack-like data structure can efficiently produce the optimal answer in linear time.
Problem Summary
Given:
A number represented as a string
sAn integer
k
Remove exactly k digits such that:
The resulting number is the smallest possible.
The relative order of the remaining digits remains unchanged.
The result does not contain leading zeros.
If all digits are removed, return
"0".
Key Idea
The optimal solution uses a greedy strategy with a stack-like structure.
The intuition is:
Smaller digits should appear earlier in the result.
If a larger digit appears before a smaller digit, removing the larger digit helps minimize the final number.
We maintain a monotonic increasing sequence of digits.
Whenever a smaller digit arrives, we remove larger digits from the end of the current result as long as removals are still available.
Why the Greedy Approach Works
Consider the number:
1432219
Suppose we can remove digits.
When we encounter:
4 followed by 3
keeping 4 before 3 makes the number larger.
Removing 4 produces:
132219
which is smaller.
This observation leads to the greedy rule:
Whenever a larger digit appears before a smaller digit, remove the larger digit if removals are still available.
Approach Explained
We iterate through each digit in the string.
Step 1: Maintain a Stack-Like Structure
Use a StringBuilder as a stack to store digits.
Step 2: Remove Larger Previous Digits
While:
k > 0The stack is not empty
The last digit in the stack is greater than the current digit
remove the last digit.
This helps create the smallest possible prefix.
Step 3: Add Current Digit
Append the current digit to the stack.
Step 4: Remove Remaining Digits
After processing all digits, there may still be removals left.
If:
k > 0
remove digits from the end of the stack.
Step 5: Remove Leading Zeros
Skip all leading zeros in the final result.
Step 6: Handle Empty Result
If the resulting string becomes empty, return:
"0"
Example Walkthrough
Input
s = "1432219"
k = 3
Processing
Read 1
Stack: 1
Read 4
Stack: 14

Join the conversation! Your thoughts help the community grow.