Remove Duplicate Letters
Master this topic with zero to advance depth.
Remove Duplicate Letters
Remove duplicate letters from string s so that every letter appears once. The result must be the smallest in lexicographical order among all possible results.
Visual Representation
s = "bcabc"
Counts: {b:2, c:2, a:1}
1. 'b': Push. Stack: [b]. Counts: {b:1, c:2, a:1}
2. 'c': Push. Stack: [b, c]. Counts: {b:1, c:1, a:1}
3. 'a':
- 'c' > 'a' and c's count > 0. Pop c.
- 'b' > 'a' and b's count > 0. Pop b.
- Push 'a'. Stack: [a]. Counts: {b:1, c:1, a:0}
4. 'b': Push. Stack: [a, b]. Counts: {b:0, c:1, a:0}
5. 'c': Push. Stack: [a, b, c]. Counts: {b:0, c:0, a:0}
Result: "abc"Examples
Level I: Generate All Subsequences, Filter, Then Sort
Intuition
Generate all unique subsequences of the string that contain each character exactly once (using a set of frequency tracking). Filter to keep valid ones and return the lexicographically smallest. This is exponential and only feasible for tiny inputs.
Level III: Optimal (Greedy Monotonic Stack)
Intuition
Maintain a stack of characters that represents the current smallest lexicographical result. Use a frequency map to know if a character will appear later. If the current character is smaller than the stack top and the stack top appears again later, pop the stack top. Use a seen set to skip characters already in the result.
Detailed Dry Run
| Char | Action | Stack | Seen | Count Left |
|---|---|---|---|---|
| 'b' | Push | [b] | {b} | b:1 |
| 'c' | Push | [b, c] | {b, c} | c:1 |
| 'a' | Pop b, c; Push a | [a] | {a} | a:0 |
| 'b' | Push | [a, b] | {a, b} | b:0 |
⚠️ Common Pitfalls & Tips
You can only pop a character if you know it appears later in the string. Character counts or last-occurrence indices are necessary.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.