Smallest Subsequence of Distinct Characters Problem
Description
LeetCode Problem 1081.
Given a string s, return the lexicographically smallest subsequence of s that contains all the distinct characters of s exactly once.
Example 1:
Input: s = "bcabc"
Output: "abc"
Example 2:
Input: s = "cbacdcbc"
Output: "acdb"
Constraints:
1 <= s.length <= 1000sconsists of lowercase English letters.
Note: This question is the same as 316: https://leetcode.com/problems/remove-duplicate-letters/
Solution
Approach: Greedy with a Monotonic Stack
Build the answer from left to right in a stack, using each distinct letter once. Record the last index at which each letter appears.
For each character c at index i:
- If
cis already in the stack, skip it. It already sits at the best place it could get. - Otherwise, while the top of the stack is a letter bigger than
cthat appears again later (its last index is greater thani), pop it. Puttingcbefore it makes the result smaller, and we can still pick that letter up later. - Push
c.
A letter that does not appear again after i is never popped, because it would be lost for good, and the answer must contain every letter. That is what stops "cbacdcbc" from becoming "abcd": when the b at index 6 arrives, the stack is a, c, d, and the d on top is bigger, but it never appears again, so it has to stay. The answer is "acdb".
A boolean array (or a set) tells us in O(1) whether a letter is in the stack.
Complexity: O(n) time, each character is pushed and popped at most once. O(1) extra space besides the answer, since the stack holds at most 26 letters.
class Solution:
def smallestSubsequence(self, s: str) -> str:
last = {c: i for i, c in enumerate(s)} # last index of each letter
stack = []
in_stack = set()
for i, c in enumerate(s):
if c in in_stack:
continue
# A bigger letter on top can wait: it appears again later.
while stack and stack[-1] > c and last[stack[-1]] > i:
in_stack.remove(stack.pop())
stack.append(c)
in_stack.add(c)
return "".join(stack)