Remove Duplicate Letters

Medium

Topics
StringStackGreedyMonotonic Stack

Given a string s, remove duplicate letters so that every letter appears exactly once. Among all such results, return the lexicographically smallest one.

Example 1

inbcabc
outabc
removed
Each letter must appear once and the result must be the smallest in alphabetical order. Result: abc.
Cells are the characters of the string; the small numbers underneath are indices.
Input:  s = "bcabc"
Output: "abc"

Example 2

incbacdcbc
outacdb
removed
Input:  s = "cbacdcbc"
Output: "acdb"
Explanation: Keeping the first c, then a, then d, then b gives the smallest arrangement in which each letter appears once.

Constraints

  • 1 <= s.length <= 10^4
  • s consists of lowercase English letters
Editorial — intuition, approach, complexity and pitfalls

Intuition

Scan left to right and keep a stack of the answer so far. A letter on the stack is only worth keeping in place if it is smaller than what follows, or if this is its last chance to appear. So when the incoming character is smaller than the stack top and that top appears again later, pop it — you can always reinsert it further right, and moving it right can only shrink the result lexicographically. The result is a monotonic stack with a "does it recur?" guard.

Approach

  1. Pre-count the remaining occurrences of every letter, or precompute each letter's last index.
  2. Walk the string. If a character is already on the stack, skip it — each letter appears exactly once in the output.
  3. Otherwise, while the stack top is greater than the current character and that top occurs again later in the string, pop it and mark it as no longer in the stack.
  4. Push the current character, mark it present, and decrement the remaining count as you pass each index.
  5. Join the stack for the answer. It is automatically the smallest valid arrangement.
class Solution:
    def removeDuplicateLetters(self, s):
        last = {ch: i for i, ch in enumerate(s)}
        stack = []
        seen = set()
        for i, ch in enumerate(s):
            if ch in seen:
                continue
            while stack and stack[-1] > ch and last[stack[-1]] > i:
                seen.discard(stack.pop())
            stack.append(ch)
            seen.add(ch)
        return "".join(stack)

Dry Run

s = "cbacdcbc".  last index of each letter: a=2, b=6, c=7, d=4
  i=0  c                                        stack "c"
  i=1  b   c is bigger and recurs at 7, so pop it    stack "b"
  i=2  a   b is bigger and recurs at 6, so pop it    stack "a"
  i=3  c                                        stack "ac"
  i=4  d                                        stack "acd"
  i=5  c   already on the stack, skip           stack "acd"
  i=6  b   d and c are bigger but neither recurs after 6, so nothing pops
                                                stack "acdb"
  i=7  c   already on the stack, skip           stack "acdb"
answer "acdb"
Three conditions gate the pop, and each is load-bearing:
  stack[-1] > c       only pop something that this letter improves on
  last[top] > i       only pop something that will come round again
  c not in used       never insert a letter twice
i=6 is where the second condition saves the answer. 'd' and 'c' both exceed 'b',
but their last occurrences are at 4 and 7 -- the d is gone for good, so popping it
would delete it from the output. Drop that guard and the answer becomes "abc",
silently losing the d. Drop the `in used` skip and it becomes "acdbc", with a
duplicate c.
Clearing the marker when popping is the one that looks like bookkeeping and is
not. Pop without `used.discard` and a letter can never be reinserted at its better
position: this input collapses to "ad" and "bcabc" to "a".
Sorting the distinct letters is not the answer. The output has to be a SUBSEQUENCE
of s, so "acdb" is the smallest reachable string, not "abcd".

Complexity

  • Time — O(n) — each character is pushed and popped at most once.
  • Space — O(1) — the stack and maps hold at most 26 letters.

Common Pitfalls

  • The last[top] > i guard is essential. Popping a letter that never recurs deletes it from the answer entirely.
  • Skipping characters already on the stack is required. Without it a letter can be emitted twice.
  • Sorting the distinct letters is not the answer. The output must be a subsequence of s, so relative order constrains what is reachable.
  • Remember to clear the "on stack" marker when you pop, or the letter can never be reinserted at its better position.

Full Solution — all languages

class Solution:
    def removeDuplicateLetters(self, s):
        last = {c: i for i, c in enumerate(s)}
        stack = []
        used = set()
        for i, c in enumerate(s):
            if c in used:
                continue
            while stack and stack[-1] > c and last[stack[-1]] > i:
                used.discard(stack.pop())
            stack.append(c)
            used.add(c)
        return "".join(stack)
SensAI
Beta
Tap the mic to stop voice mode