Talentd
FleetCode

1081. Smallest Subsequence of Distinct Characters

Medium70.6% acceptance5 companies

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

Example 1:

Input: s = "bcabc"
Output: "abc"

Example 2:

Input: s = "cbacdcbc"
Output: "acdb"

Constraints:

  • 1 <= s.length <= 1000
  • s consists of lowercase English letters.
Note: This question is the same as 316: https://leetcode.com/problems/remove-duplicate-letters/

Hints open one at a time

Hint 1
Greedily try to add one missing character. How to check if adding some character will not cause problems ? Use bit-masks to check whether you will be able to complete the sub-sequence if you add the character at some index i.
9:25
Still stuck?Read 3 approaches, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def smallestSubsequence(self, s: str) -> str:
3
Starter codePython 3Spaces: 4
Examples
Input
"bcabc"
Input
"cbacdcbc"
Your code is saved on this device.Solution