Smallest Subsequence of Distinct Characters - Problem

Given a string s, return the lexicographically smallest subsequence of s that contains all the distinct characters of s exactly once.

A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.

Example: For string "bcabc", we need to select one occurrence of each character ('a', 'b', 'c') such that the result is lexicographically smallest while maintaining the original order.

Input & Output

Example 1 — Basic Case
$ Input: s = "bcabc"
Output: "abc"
💡 Note: We need each distinct character (a,b,c) exactly once. The lexicographically smallest subsequence maintaining original order is "abc"
Example 2 — All Different
$ Input: s = "ecbacba"
Output: "eacb"
💡 Note: Distinct characters are {a,b,c,e}. The optimal subsequence is "eacb" - we can't improve it while maintaining order
Example 3 — Single Character
$ Input: s = "aaaa"
Output: "a"
💡 Note: Only one distinct character 'a', so result is just "a"

Constraints

  • 1 ≤ s.length ≤ 1000
  • s consists of lowercase English letters

Visualization

Tap to expand
Smallest Subsequence of Distinct Characters INPUT String s = "bcabc" b 0 c 1 a 2 b 3 c 4 Last Occurrences: a: 2, b: 3, c: 4 Distinct Chars: a b c ALGORITHM STEPS 1 Count last index Track last occurrence of each character 2 Use stack + seen set Stack for result, set tracks included 3 Pop larger chars If stack top > current and appears later, pop 4 Push current char Add to stack and mark as seen Stack builds: [] --> [b] --> [bc] --> [a] --> [ab] --> [abc] c b a stack FINAL RESULT Lexicographically Smallest Subsequence with all distinct chars: a b c Output: "abc" [OK] Valid Result - Contains all distinct chars - Each char appears once - Smallest lex order - Valid subsequence of "bcabc" "abc" < "acb" < "bac" ... Key Insight: The greedy approach works by maintaining a monotonic stack. When processing each character, we pop larger characters from the stack only if they appear later in the string (can be re-added). This ensures we always pick the lexicographically smallest valid character at each position. TutorialsPoint - Smallest Subsequence of Distinct Characters | Greedy - First Valid Characters
Asked in
Google 15 Amazon 12 Facebook 8
23.4K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen