Leetcode 1081: Smallest Subsequence of Distinct Characters

grid47
grid47
Exploring patterns and algorithms
Jul 21, 2024 6 min read

You are given a string s, and your task is to return the lexicographically smallest subsequence of s that contains all the distinct characters of s exactly once. The subsequence must be in the same order as the original string, but the characters should not repeat.
Problem
Approach
Steps
Complexity
Input: The input consists of a string s that contains lowercase English letters.
Example: Input: s = "zabcde"
Constraints:
• 1 <= s.length <= 1000
• s consists of lowercase English letters.
Output: The output should be the lexicographically smallest subsequence containing all the distinct characters of s exactly once.
Example: Output: "abcde"
Constraints:
• The subsequence should preserve the order of the original string.
Goal: The goal is to find the lexicographically smallest subsequence of the string containing each distinct character exactly once while maintaining the order.
Steps:
• 1. Count the last occurrence index of each character in the string.
• 2. Traverse the string and construct the result by considering whether to add each character based on its lexicographical order and ensuring that it doesn't repeat.
Goal: The solution must efficiently handle strings with up to 1000 characters.
Steps:
• 1 <= s.length <= 1000
• s consists of lowercase English letters.
Assumptions:
• The input string is non-empty and contains lowercase English letters.
Input: Input: s = "bcabc"
Explanation: In this example, the lexicographically smallest subsequence that contains all the distinct characters exactly once is "abc".

Input: Input: s = "cbacdcbc"
Explanation: In this case, the lexicographically smallest subsequence is "acdb".

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus