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
Remove Duplicate Letters: "bcabc" → "abc"bcabcKeepRemoveKeepRemoveRemoveSmart Strategy: Remove 'c' and 'b' when we see 'a'because both 'c' and 'b' appear later and are > 'a'abcResult: "abc" - Lexicographically SmallestAlgorithm:1. Count frequencies2. Use monotonic stack3. Remove larger chars when they appear laterTime: O(n)Space: O(1)
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
Asked in
Google 15 Amazon 12 Facebook 8 Microsoft 6
85.0K Views
Medium Frequency
~25 min Avg. Time
2.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen