Smallest Subsequence of Distinct Characters (LeetCode 1081): Solution and Explanation

Medium
String
Stack
Greedy
Monotonic stack

Return the lexicographically smallest subsequence of s that uses every distinct letter exactly once. For bcabc the answer is abc, and for cbacdcbc it is acdb.

Intuition

Every distinct letter must appear once, so the only real choice is which copy of each letter to keep. A small letter should come as early as it can.

Scan left to right and keep the answer on a stack. When a smaller letter arrives, the bigger letter on top would be better placed after it, but you can only move it if another copy is still coming.

Keep a count of how many copies of each letter are still ahead. A top letter with a count above zero can be popped and picked up again later. A top letter with a count of zero is locked in place.

Approach: Greedy monotonic stack with remaining counts

  1. Count every letter in s.
  2. Scan s. For each letter ch, decrement its count, since this copy is no longer ahead.
  3. If ch is already in the stack, skip it.
  4. While the top is bigger than ch and its count is above zero, pop it and mark it unused.
  5. Push ch and mark it used.
  6. Join the stack from bottom to top.

Step-by-step example

s = "bcabc"
  1. Counts: a 1, b 2, c 2.
  2. Read b, count of b drops to 1. Stack empty, push. Stack: b.
  3. Read c, count of c drops to 1. Top b is smaller, push. Stack: bc.
  4. Read a, count of a drops to 0. Top c is bigger with 1 copy ahead, pop. Top b is bigger with 1 copy ahead, pop. Push a. Stack: a.
  5. Read b, count drops to 0. Top a is smaller, push. Stack: ab.
  6. Read c, count drops to 0. Push. Stack: abc, the answer.

Code: Python, Java, C++

1class Solution:
2    def smallestSubsequence(self, s: str) -> str:
3        left = {}
4        for ch in s:
5            left[ch] = left.get(ch, 0) + 1
6        stack = []
7        used = set()
8        for ch in s:
9            left[ch] -= 1
10            if ch in used:
11                continue
12            while stack and stack[-1] > ch and left[stack[-1]] > 0:
13                used.remove(stack.pop())
14            stack.append(ch)
15            used.add(ch)
16        return "".join(stack)
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each character is read once, and each push is undone by at most one pop.

Space

O(1)

The counts, the used flags and the stack each hold at most 26 letters.

Other approaches

Last-index table instead of counts (time O(n), space O(1))

Store the last index of each letter and pop the top only if its last index is after the current position. It is the same algorithm with a different test for whether a later copy exists.

Pick the smallest safe letter each round (time O(26 * n), space O(n))

Repeatedly choose the smallest letter whose first remaining position still leaves every other needed letter after it, then cut the string there. Easy to prove, but each round rescans the string.

Common mistakes

  • Decrementing the count after the skip check. A skipped copy still has to be removed from the supply, or a later pop will believe a copy remains when it does not.
  • Popping a bigger letter whose count is zero. That was its last copy, so it would vanish from the answer.
  • Popping a letter from the stack without clearing its used flag, which makes a later copy get skipped.
  • Pushing a letter that is already in the stack, which breaks the one-of-each rule.

Frequently asked questions

Is this the same as Remove Duplicate Letters?

Yes. LeetCode 316 asks the identical question, only the input limit differs. The same stack solution solves both.

Why is skipping a letter already in the stack safe?

Every letter above it in the stack was pushed later and survived comparison with it, so moving it to a later spot would only put bigger letters first, which never makes the string smaller.

Why use counts rather than last indexes?

Either works. A count answers the question how many copies are still ahead directly, and it does not need a second pass to find positions.