Problem Description
Given a string s, return the lexicographically smallest subsequence of s that contains all the distinct characters of s exactly once.
Key Insights
- Each unique character must appear exactly once in the result.
- The selected subsequence should be lexicographically smallest.
- Utilize a monotonic stack to maintain order and allow removal of characters that can appear later.
- Maintain a frequency counter to decide if it is safe to remove a character from the current sequence.
- Use a greedy strategy: for every character, remove all previous characters that are lexicographically larger and still available later.
Space and Time Complexity
Time Complexity: O(n) as we process each character in the string once. Space Complexity: O(n) for the stack and auxiliary data structures (frequency counter and set).
Solution
The solution leverages a greedy algorithm along with a monotonic stack. First, count the occurrences of every character in the string. Then, iterate over the string and for each character:
- Decrement its count.
- Skip the character if it is already in the result (tracked via a set).
- Remove characters from the stack that are greater than the current character and that will appear again later (their frequency is still positive).
- Add the current character to the stack. At the end, the stack represents the lexicographically smallest subsequence containing distinct characters exactly once.