Remove Duplicate Letters - Problem
Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.
Lexicographical order means dictionary order - for example, "abc" comes before "acb" because 'b' < 'c' at the first differing position.
The key challenge is not just removing duplicates, but doing so while maintaining the lexicographically smallest possible result.
Input & Output
Example 1 — Basic Case
$
Input:
s = "bcabc"
›
Output:
"abc"
💡 Note:
We need one occurrence of each letter: a, b, c. The lexicographically smallest arrangement is "abc". We can remove the duplicate 'b' at index 3 and duplicate 'c' at index 4.
Example 2 — Different Order
$
Input:
s = "cbacdcbc"
›
Output:
"acdb"
💡 Note:
Unique letters are: a, b, c, d. The lexicographically smallest string containing all of them exactly once is "acdb". Note that "abcd" is not possible given the character positions in the original string.
Example 3 — Already Optimal
$
Input:
s = "abc"
›
Output:
"abc"
💡 Note:
All characters are unique and already in lexicographically smallest order, so no changes needed.
Constraints
- 1 ≤ s.length ≤ 104
- s consists of lowercase English letters
Visualization
Tap to expand
Understanding the Visualization
1
Input Analysis
String "bcabc" has duplicates: b(2), c(2), a(1)
2
Smart Removal
Use monotonic stack to decide which duplicates to remove
3
Optimal Output
Result "abc" is lexicographically smallest with all unique letters
Key Takeaway
🎯 Key Insight: Use a monotonic stack to greedily build the lexicographically smallest result by removing larger characters when we know they can be added back later
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code