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 <= 1000s consists of lowercase English letters.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:
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:
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]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:
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)| Case | How to Handle |
|---|---|
| Empty string input | Return an empty string immediately since no characters exist to form a subsequence. |
| String with all identical characters | The frequency and tracking mechanism will keep only the single last occurrence of the character. |
| String with all unique characters in descending order | The monotonic stack logic will reverse the order to produce the ascending lexicographical sequence. |
| String with all unique characters in ascending order | The stack will push each character without popping since no preceding character is larger and needed later. |
| Interleaved characters requiring greedy stack pops | 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 | 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 | A boolean visited array instantly skips characters that are already included in the final subsequence. |