Taro Logo

Smallest Subsequence of Distinct Characters

#150 Most AskedMedium
0 views
Topics:
StringsStacksGreedy Algorithms

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/

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the character set of the input string `s`? Can we assume it only contains lowercase English letters?
  2. What should be returned if the input string `s` is empty?
  3. Since the problem asks for a subsequence rather than a substring, are we allowed to skip characters from the original string as long as we maintain their relative order?
  4. How should we handle memory or performance constraints if the input string is extremely large?
  5. Is the output guaranteed to be unique since we are looking for the 'lexicographically smallest' subsequence containing all distinct characters exactly once?

Brute Force Solution

Approach

Imagine you have a jumble of letters and you need to pick out a shorter string of letters that uses every unique character at least once while staying as short and alphabetically neat as possible. The brute force approach is like trying every single combination of letters you can possibly make from the original word and checking which ones contain all the unique characters.

Here's how the algorithm would work step-by-step:

  1. First, list out every possible combination of letters that you can form by picking some letters from the original text in the order they appear.
  2. Go through each of those combinations one by one and check if it contains every single unique character found in the original text.
  3. Throw away any combination that is missing even one of the unique characters.
  4. For the combinations that do contain every unique character, look at how they are spelled out.
  5. Compare these valid combinations alphabetically to see which one comes first in the dictionary.
  6. Select that first-appearing combination as your final answer.

Code Implementation

def smallestSubsequence(input_string):
    from itertools import combinations

    unique_characters = set(input_string)
    
    # Generate all possible subsequences preserving original relative order of characters
    all_subsequences = []
    for subsequence_length in range(1, len(input_string) + 1):
        for index_combination in combinations(range(len(input_string)), subsequence_length):
            current_subsequence = "".join(input_string[index] for index in index_combination)
            all_subsequences.append(current_subsequence)

    # Filter out combinations that do not include all unique characters from the original string
    valid_combinations = [sub for sub in all_subsequences if set(sub) == unique_characters]

    # Sort valid combinations lexicographically to find the smallest alphabetical option
    valid_combinations.sort()

    return valid_combinations[0]

Big(O) Analysis

Time Complexity
O(2^n * n) – The brute force approach generates all possible subsequences from the input string of size n, which results in 2^n total combinations. For each of these 2^n combinations, we must iterate through the string to check if it contains all unique characters and to compare it alphabetically, where each check takes up to n operations. This leads to approximately 2^n * n operations, which simplifies to the exponential Big O time complexity of O(2^n * n).
Space Complexity
O(N) – The brute force approach described requires generating and storing every possible combination of letters derived from the original text of length N. Additionally, keeping track of valid combinations and checking their unique characters requires intermediate storage for these subsets. As the input size N grows, the number of combinations and the extra memory needed to hold them increases exponentially in the worst case, though standard stack-based or frequency-map solutions for this problem optimize auxiliary space by storing at most 26 unique characters, bound by the alphabet size.

Optimal Solution

Approach

To find the smallest possible sequence containing every unique letter, we can build our result step by step while keeping alphabetical order in mind. We use a clever helper strategy that allows us to remove letters we already picked if a better, smaller letter appears later and our current letter still has more copies waiting further down the line.

Here's how the algorithm would work step-by-step:

  1. First, count how many times each letter appears in the entire text so we always know if a letter will show up again later.
  2. Begin walking through the text from the very beginning to the end, looking at one letter at a time.
  3. Before adding the current letter to our growing collection, check if we have already included it; if we have, simply skip ahead because we only want each unique letter once.
  4. Look at the last letter we successfully added to our collection. If that previous letter is alphabetically larger than our current letter, and we are guaranteed to see that previous letter again later in the text, remove it from our collection to make room for the better, smaller letter.
  5. Repeat this removal check as many times as necessary with the previous letters in our collection.
  6. Finally, add the current letter to our collection and move on to examine the next letter in the text.
  7. Once you reach the end of the text, read off the final collection of letters in order to get the correct answer.

Code Implementation

def smallest_subsequence(input_string):
    last_seen_indices = {}

    for current_index, character in enumerate(input_string):
        last_seen_indices[character] = current_index

    result_stack = []
    visited_set = set()

    for current_index, character in enumerate(input_string):
        if character in visited_set:
            continue

        # We remove larger characters if they appear later, ensuring a lexicographically smaller result.
        while result_stack and result_stack[-1] > character and last_seen_indices[result_stack[-1]] > current_index:
            removed_character = result_stack.pop()
            visited_set.remove(removed_character)

        result_stack.append(character)
        visited_set.add(character)

    # Convert the character collection back into a string format to return the final answer.
    return "".join(result_stack)

Big(O) Analysis

Time Complexity
O(n) – To analyze the time complexity, let n be the length of the input text. Counting the frequency of each letter takes one pass over the string, which costs O(n) operations. Then, as we iterate through the text character by character, each character is pushed onto and popped from our collection at most once. This ensures that the inner removal checks do not re-scan the string, meaning the total work scales linearly with n. Summing these passes together results in approximately 2n operations, which simplifies to O(n).
Space Complexity
O(1) – The algorithm utilizes an auxiliary frequency array or hash map to store the counts of each character, which requires a fixed size of 26 since the alphabet is limited to lowercase English letters regardless of the input length N. Additionally, the result collection and tracking mechanisms hold at most 26 unique characters at any given time. Because these data structures do not scale with the input size N and remain constant, the overall auxiliary space complexity simplifies to Big O of 1.

Edge Cases

Empty string input
How to Handle:
Return an empty string immediately since no characters exist to form a subsequence.
String with all identical characters
How to Handle:
The frequency and tracking mechanism will keep only the single last occurrence of the character.
String with all unique characters in descending order
How to Handle:
The monotonic stack logic will reverse the order to produce the ascending lexicographical sequence.
String with all unique characters in ascending order
How to Handle:
The stack will push each character without popping since no preceding character is larger and needed later.
Interleaved characters requiring greedy stack pops
How to Handle:
The algorithm pops larger elements from the stack only if they appear again later in the remaining string.
Maximum length strings up to the constraint limit
How to Handle:
A linear scan with a frequency array and stack ensures an efficient O(N) time complexity without TLE.
Characters already present in the result stack
How to Handle:
A boolean visited array instantly skips characters that are already included in the final subsequence.
0/257 completed