Remove Duplicate Letters (LeetCode 316): Solution and Explanation
Keep exactly one copy of every letter in s, in the original relative order, and return the lexicographically smallest string you can get. For bcabc the answer is abc, and for cbacdcbc it is acdb.
Intuition
The answer must contain every distinct letter once, so the only freedom is which copy of each letter to keep. To make the string small, small letters should come as early as possible.
Build the answer from left to right. When a letter arrives that is smaller than the last letter you kept, the string would be smaller if the bigger letter moved after it. You can do that only if the bigger letter shows up again later, because then you can take that later copy instead.
That rule is a monotonic stack with one extra condition. Pop the top while it is bigger than the current letter and has a later copy. A letter on its last copy is pinned in place. Letters already on the stack are skipped, since their position is already the best one.
Approach: Greedy monotonic stack with last-occurrence check
- Record the last index of every letter in
s. - Keep a stack of chosen letters and a set of letters currently on the stack.
- For each index
iwith letterch: ifchis already on the stack, skip it. - While the stack top is bigger than
chand its last index is greater thani, pop it and remove it from the set. - Push
chand add it to the set. - Join the stack from bottom to top and return it.
Step-by-step example
s = "bcabc"
- Last indexes: a at 2, b at 3, c at 4.
- Read
bat 0. The stack is empty, push it. Stack:b. - Read
cat 1. Topbis smaller, so push. Stack:bc. - Read
aat 2. Topcis bigger and appears again at 4, pop it. Topbis bigger and appears again at 3, pop it. Pusha. Stack:a. - Read
bat 3. Topais smaller, push. Stack:ab. - Read
cat 4. Topbis smaller, push. Stack:abc, which is the answer.
Code: Python, Java, C++
1class Solution:
2 def removeDuplicateLetters(self, s: str) -> str:
3 last = {ch: i for i, ch in enumerate(s)}
4 stack = []
5 seen = set()
6 for i, ch in enumerate(s):
7 if ch in seen:
8 continue
9 while stack and stack[-1] > ch and last[stack[-1]] > i:
10 seen.remove(stack.pop())
11 stack.append(ch)
12 seen.add(ch)
13 return "".join(stack)1class Solution {
2 public String removeDuplicateLetters(String s) {
3 int[] last = new int[26];
4 for (int i = 0; i < s.length(); i++) last[s.charAt(i) - 'a'] = i;
5 StringBuilder stack = new StringBuilder();
6 boolean[] seen = new boolean[26];
7 for (int i = 0; i < s.length(); i++) {
8 char ch = s.charAt(i);
9 if (seen[ch - 'a']) continue;
10 while (stack.length() > 0 && stack.charAt(stack.length() - 1) > ch && last[stack.charAt(stack.length() - 1) - 'a'] > i) {
11 seen[stack.charAt(stack.length() - 1) - 'a'] = false;
12 stack.deleteCharAt(stack.length() - 1);
13 }
14 stack.append(ch);
15 seen[ch - 'a'] = true;
16 }
17 return stack.toString();
18 }
19}1class Solution {
2public:
3 string removeDuplicateLetters(string s) {
4 vector<int> last(26, 0);
5 for (int i = 0; i < (int)s.size(); i++) last[s[i] - 'a'] = i;
6 string stack;
7 vector<bool> seen(26, false);
8 for (int i = 0; i < (int)s.size(); i++) {
9 char ch = s[i];
10 if (seen[ch - 'a']) continue;
11 while (!stack.empty() && stack.back() > ch && last[stack.back() - 'a'] > i) {
12 seen[stack.back() - 'a'] = false;
13 stack.pop_back();
14 }
15 stack.push_back(ch);
16 seen[ch - 'a'] = true;
17 }
18 return stack;
19 }
20};Time and space complexity
O(n)
Each index is read once, and each push is matched by at most one pop, so the total work is linear.
O(1)
The stack, the set and the last-index table each hold at most 26 letters.
Other approaches
Pick the smallest valid letter repeatedly (time O(26 * n), space O(n))
Find the smallest letter whose first position still leaves every other remaining letter available after it, take it, cut the string after that position, delete that letter everywhere, and recurse. It is correct and easy to argue about, but each round scans the string.
Try every subsequence (time Exponential, space O(n))
Generate every way to keep one copy of each letter and keep the smallest. This is only useful to check answers on tiny inputs.
Common mistakes
- Popping a bigger letter without checking that it appears again later. If it was the last copy, the letter disappears from the answer.
- Forgetting to skip letters already on the stack. Pushing a second copy breaks the one-of-each rule, and popping the first one to make room is never better.
- Removing a popped letter from the stack but not from the seen set, so a later copy of it is wrongly skipped.
- Comparing with the current index using
>=instead of>for the last occurrence. At the last copy itself there is nothing left to take later.
Frequently asked questions
Why is it safe to skip a letter that is already on the stack?
The copy already on the stack sits where it gives the smallest prefix so far. Every letter stacked after it survived being compared against it, so moving it later can only put a bigger letter first, which never helps.
How is this related to Remove K Digits?
Both use a stack that pops a bigger element when a smaller one arrives. Remove K Digits limits pops with a budget of k, while here a pop is allowed only if the popped letter appears again later.
Is this the same problem as Smallest Subsequence of Distinct Characters?
Yes. LeetCode 1081 asks the same question with a different title, and the same stack solution solves it.
Why is the space O(1) and not O(n)?
The alphabet has 26 lowercase letters, and each letter is on the stack at most once, so every structure is bounded by 26 no matter how long the input is.