Remove Duplicate Letters - Problem
You're given a string containing lowercase letters, and your mission is to create the lexicographically smallest string possible while ensuring each letter appears exactly once.
This is a classic greedy problem that requires strategic thinking! You need to remove duplicate letters, but not just any removal will do - you must produce the smallest possible result when compared alphabetically.
Example: Given "bcabc", you could form "bca", "cab", or "abc" - but "abc" is lexicographically smallest!
Think of it like arranging books on a shelf - you want the alphabetically earliest arrangement possible using each book exactly once.
Input & Output
example_1.py โ Basic Case
$
Input:
s = "bcabc"
โบ
Output:
"abc"
๐ก Note:
We have letters 'b', 'c', and 'a'. Since 'a' comes first alphabetically, we want it first. We can form 'abc' by taking the first 'b', first 'c', then 'a', then we need 'b' and 'c' again - but we can get them from the remaining characters.
example_2.py โ Different Order
$
Input:
s = "cbacdcbc"
โบ
Output:
"acdb"
๐ก Note:
We have letters 'c', 'b', 'a', 'd'. The lexicographically smallest arrangement is 'acdb'. We need to be strategic about which occurrences of each character to keep.
example_3.py โ Single Character
$
Input:
s = "ecbacba"
โบ
Output:
"eacb"
๐ก Note:
With characters 'e', 'c', 'b', 'a', the optimal arrangement starts with 'e' (appears only once), then 'a' (earliest alphabetically), followed by 'c' and 'b'.
Constraints
- 1 โค s.length โค 104
- s consists of lowercase English letters
- Each character must appear exactly once in the result
Visualization
Tap to expand
Understanding the Visualization
1
Count Inventory
First, count how many copies of each book (character) you'll receive total
2
Process Books
As each book arrives, decide if you should replace books already on shelf
3
Smart Replacement
Remove a book from shelf only if: (1) new book comes alphabetically earlier, (2) you'll get the removed book again later
4
Final Arrangement
The stack naturally maintains the lexicographically smallest arrangement
Key Takeaway
๐ฏ Key Insight: The monotonic stack approach works because we can "undo" decisions when we encounter a character that should come earlier, as long as we know that character will appear again later in the string.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code