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 Greedy with Monotonic Stack Approach INPUT String s = "bcabc" b idx 0 c idx 1 a idx 2 b idx 3 c idx 4 Last Occurrence Index char last a 2 b 3 c 4 Track last index of each char to know if we can remove it ALGORITHM STEPS 1 Process 'b' Stack empty, push b b 2 Process 'c' c > b, push c bc 3 Process 'a' a < c, c appears later Pop c. a < b, b later Pop b. Push a a 4 Process 'b' b > a, push b ab 5 Process 'c' c > b, push c abc Monotonic increasing stack maintains lex order FINAL RESULT Stack contents form result: a b c Output: "abc" [OK] Lexicographically Smallest Each letter appears exactly once "abc" comes before "bac", "bca", "cab", "cba" in dictionary order Input: "bcabc" --> Output: "abc" Duplicates b,c removed optimally Key Insight: Use a monotonic stack to maintain lexicographical order. Before pushing a character, pop larger characters from the stack IF they appear later in the string (we can add them back). Track "in_stack" to avoid duplicates. Time: O(n) - each char pushed/popped at most once. Space: O(26) for tracking unique letters. TutorialsPoint - Remove Duplicate Letters | Greedy with Monotonic Stack Approach
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