Remove Duplicate Letters
Medium
Topics
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
abc.Input: s = "bcabc" Output: "abc"
Example 2
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
- Pre-count the remaining occurrences of every letter, or precompute each letter's last index.
- Walk the string. If a character is already on the stack, skip it — each letter appears exactly once in the output.
- 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.
- Push the current character, mark it present, and decrement the remaining count as you pass each index.
- 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] > iguard 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)import java.util.*;
class Solution {
public String removeDuplicateLetters(String s) {
int[] last = new int[128];
Arrays.fill(last, -1);
for (int i = 0; i < s.length(); i++) last[s.charAt(i)] = i;
StringBuilder stack = new StringBuilder();
boolean[] used = new boolean[128];
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (used[c]) continue;
while (stack.length() > 0) {
char top = stack.charAt(stack.length() - 1);
if (top > c && last[top] > i) {
used[top] = false;
stack.deleteCharAt(stack.length() - 1);
} else break;
}
stack.append(c);
used[c] = true;
}
return stack.toString();
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: string removeDuplicateLetters(string s) {
vector<int> last(128, -1);
for (size_t i = 0; i < s.size(); i++) last[(unsigned char)s[i]] = (int)i;
string stack;
vector<char> used(128, 0);
for (size_t i = 0; i < s.size(); i++) {
char c = s[i];
if (used[(unsigned char)c]) continue;
while (!stack.empty() && stack.back() > c && last[(unsigned char)stack.back()] > (int)i) {
used[(unsigned char)stack.back()] = 0;
stack.pop_back();
}
stack += c;
used[(unsigned char)c] = 1;
}
return stack;
}
};/**
* @param {string} s
* @return {string}
*/ var removeDuplicateLetters = function(s) {
const last = new Map();
for (let i = 0; i < s.length; i++) last.set(s[i], i);
const stack = [], used = new Set();
for (let i = 0; i < s.length; i++) {
const c = s[i];
if (used.has(c)) continue;
while (stack.length && stack[stack.length - 1] > c && last.get(stack[stack.length - 1]) > i) {
used.delete(stack.pop());
}
stack.push(c);
used.add(c);
}
return stack.join("");
};