Smallest Subsequence Containing Each Letter Once
Stacks & QueuesAuto-graded · 22 test casesLast updated
Build the lexicographically smallest subsequence that uses every distinct letter of a string exactly once, using a greedy monotonic stack with remaining-count tracking.
Smallest Subsequence of Distinct Letters
You are given a string text made of lowercase English letters. Produce a new string that:
- is a subsequence of
text(its characters appear in the same relative order as intext, with some characters possibly deleted), - contains every distinct letter that occurs in
textexactly once, and - is the lexicographically smallest string among all strings satisfying the two rules above.
Return that string.
Lexicographic order is the usual dictionary order: compare two strings at the first position where they differ, and the one with the smaller letter there is smaller.
Notes
- If every character in
textis the same, the answer is that single character. - If all characters are already distinct, no deletion is possible, so the answer is
textitself. - A small letter that appears only near the end cannot be moved forward; the order of the kept characters must follow the original string.
Constraints
1 <= len(text) <= 10^4textconsists only of lowercase English letters ('a'to'z').
Examples
Example 1
Input: smallest_distinct_subsequence('bcabc')
Output: 'abc'
Example 2
Input: smallest_distinct_subsequence('cbacdcbc')
Output: 'acdb'
Hints
Hint 1
Think about which letter should come first in the answer: the smallest letter whose chosen occurrence still leaves every other distinct letter available somewhere after it.
Hint 2
Scan left to right while keeping a stack of chosen letters. When a new letter is smaller than the stack top, the top can be discarded only if that letter appears again later in the string.
Hint 3
Track how many occurrences of each letter remain unprocessed, plus a set or boolean array of letters currently on the stack. Skip a character that is already on the stack.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Use a greedy monotonic stack.
- Count how many times each letter occurs in
text. This count is decremented as we scan, so it always means "occurrences not yet processed". - Scan the string from left to right. For each character
ch:- Decrement its remaining count, since this occurrence is now being processed.
- If
chis already on the stack, skip it. The copy already placed is at least as good. - Otherwise, while the stack is non-empty, its top is greater than
ch, and the top letter still occurs later (remaining count above zero), pop the top. That letter can be placed again later, afterch, which yields a smaller string. - Push
chand mark it as on the stack.
- The stack contents, read from bottom to top, form the answer.
Why it works
- Popping is safe. If the top letter
tis larger thanchand appears again later, then placingchwheretwas gives a smaller string at the first differing position, andtis still available afterwards, so no required letter is lost. - Not popping when necessary. If
tnever appears again, removing it would lose a required letter. Ift <= ch, keepingtis already at least as good. The loop stops in both cases, and since pops only happen at the top, everything beneath is protected too. - Skipping a duplicate is safe. If
chis already on the stack, then it was not displaced by any smaller letter that came after it, so moving it to a later position cannot make the string smaller. - Invariant. After each step the stack is the smallest valid prefix that can still be completed from the remaining characters, and every letter not on the stack still has occurrences left.
Complexity
- Time: O(n). Each character is pushed at most once and popped at most once, and every check is O(1).
- Space: O(1) auxiliary for the fixed 26-letter alphabet (the count and membership arrays have size 26, and the stack holds at most 26 letters).
Reference solution
def smallest_distinct_subsequence(text: str) -> str:
remaining = [0] * 26
for ch in text:
remaining[ord(ch) - ord('a')] += 1
stack = []
in_stack = [False] * 26
for ch in text:
idx = ord(ch) - ord('a')
remaining[idx] -= 1
if in_stack[idx]:
continue
while stack:
top_idx = ord(stack[-1]) - ord('a')
if stack[-1] <= ch or remaining[top_idx] == 0:
break
in_stack[top_idx] = False
stack.pop()
stack.append(ch)
in_stack[idx] = True
return ''.join(stack)