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: "bcabc" → "abc"bcabcInput StringMonotonic Stack ProcessingabcOutput: "abc"✓ Lexicographically smallest with all distinct characters
Understanding the Visualization
1
Input Analysis
String "bcabc" has distinct characters {a,b,c}
2
Build Optimal
Use monotonic stack to maintain increasing order
3
Result
Lexicographically smallest subsequence "abc"
Key Takeaway
🎯 Key Insight: Use monotonic stack to remove larger characters when smaller ones can replace them later
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