KatInterview

Smallest Subsequence Containing Each Letter Once

Stacks & QueuesAuto-graded · 22 test cases
MediumAuto-gradedStacks & Queuesmonotonic-stackgreedystrings

Last 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 in text, with some characters possibly deleted),
  • contains every distinct letter that occurs in text exactly 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 text is the same, the answer is that single character.
  • If all characters are already distinct, no deletion is possible, so the answer is text itself.
  • 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^4
  • text consists 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.