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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code