Remove Duplicate Letters Problem
Description
LeetCode Problem 316.
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.
Example 1:
Input: s = "bcabc"
Output: "abc"
Example 2:
Input: s = "cbacdcbc"
Output: "acdb"
Constraints:
- 1 <= s.length <= 10^4
- s consists of lowercase English letters.
Solution
Approach: Greedy Monotonic Stack
We build the answer from left to right and want each position to hold the smallest letter we can afford. A stack holds the answer so far. For each letter of s:
- If the letter is already in the stack, skip it. It was placed earlier, and moving it later could only make the result bigger.
- While the top of the stack is bigger than the current letter and that top letter appears again later in
s, pop it. Putting the smaller letter first makes the result smaller, and we lose nothing: the popped letter will be pushed again when we meet its later copy. - Push the current letter.
At the end, the stack read from bottom to top is the answer.
To answer "does it appear again later" in O(1), first record lastIndex[letter], the last position of each letter. A top letter whose lastIndex is before the current position is its last copy, so it must stay, and so must everything under it.
Example with s = "cbacdcbc": c is pushed, then b pops c (another c comes later), then a pops b. Next come c, then d. The following c is already in the stack and is skipped. Then b cannot pop d, because this d is the last one, so b is pushed after it. The answer is "acdb".
The detail people miss is step 1: without the "already in the stack" check, a repeated letter could pop letters that are needed and be added twice.
Complexity: O(n) time, where n is the length of s: each letter is pushed and popped at most once. O(1) extra space besides the answer, since there are only 26 letters.
class Solution:
def removeDuplicateLetters(self, s: str) -> str:
last_index = {letter: i for i, letter in enumerate(s)} # last position of each letter
stack = [] # the answer so far, kept as small as possible
in_stack = set()
for i, letter in enumerate(s):
if letter in in_stack:
continue # already placed at a better (earlier) spot
# A bigger letter on top can go if it appears again later: we will add it back then.
while stack and stack[-1] > letter and last_index[stack[-1]] > i:
in_stack.remove(stack.pop())
stack.append(letter)
in_stack.add(letter)
return "".join(stack)