Taro Logo

Remove Duplicate Letters

#11 Most AskedMedium
0 views
Topics:
StringsStacksGreedy Algorithms

Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.

Example 1:

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

Example 2:

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

Constraints:

  • 1 <= s.length <= 104
  • s consists of lowercase English letters.

Note: This question is the same as 1081: https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/

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 maximum length of the input string, and does it contain only lowercase English letters?
  2. How should we handle an empty string or a string with a single character as input?
  3. Can I assume that the input string will always contain at least one valid character, or could it be completely empty?
  4. Could you clarify the definition of 'lexicographical order' in the context of how we compare characters (standard ASCII/alphabetical order)?
  5. Is the relative order of characters strictly required to match their original relative appearance in the input string?

Brute Force Solution

Approach

Imagine you have a jumbled bag of letter tiles and want to spell out the shortest possible word that uses every unique letter at least once, but in the most alphabetically pleasing order. The brute force approach works by generating every single combination of the letters, checking which ones contain all the unique characters, and then sorting through those valid results to find the one that comes first in the alphabet.

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

  1. Start by looking at the entire jumbled sequence of letters from beginning to end.
  2. List out every possible way you could rearrange subsets of these letters, trying every single combination one by one.
  3. For every single combination you try, check two things: does it use every unique letter from the original pile at least once, and does it avoid using any letter more times than necessary.
  4. Throw away any combination that misses a letter or uses a letter too many times.
  5. Keep a running collection of all the combinations that successfully pass this check.
  6. Compare all the successful combinations side by side to see which one comes first in standard alphabetical order.
  7. Pick that very first alphabetical winner as your final answer.

Code Implementation

Big(O) Analysis

Time Complexity
O(2^n * n) – For a string of length n, the brute force approach generates every possible subset combination, resulting in 2^n total subsets to evaluate. For each of these 2^n combinations, we must perform checks that take proportional to n time to verify unique character inclusion and validate lengths. Multiplying the 2^n subset generation steps by the n work per combination yields approximately 2^n * n operations, which simplifies to O(2^n * n).
Space Complexity
O(N) – The auxiliary space is driven by the running collection of successful combinations and the intermediate subset states generated during the search. As the input size N grows, storing every valid combination and keeping track of visited letters across all possible subsets requires extra memory that scales with the number of generated permutations and combinations. The recursive exploration of every subset adds up to a maximum depth proportional to N. Ultimately, the total extra memory simplifies to Big O of N.

Optimal Solution

Approach

The optimal strategy is like building a collection of unique items one by one while keeping them in alphabetical order. We carefully look at each letter in order, making sure we only keep the best possible arrangement by replacing earlier choices if a better letter comes along later and our previous choices still appear 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 message so we always know if we can safely discard a letter and trust that another one will show up later.
  2. Begin looking at the letters one by one from the start to the end of the message.
  3. Keep a running pile of your selected letters, making sure each unique letter appears only once.
  4. Before adding a new letter to your pile, check the letter sitting at the top of your pile.
  5. If the top letter of your pile is alphabetically bigger than the new letter, and you are guaranteed to see that big letter again later in the message, remove it from your pile.
  6. Repeat this check so that you clear out any unnecessarily large letters that can be retrieved later.
  7. Finally, place the new letter into your pile and continue until you have reviewed every letter in the message.

Code Implementation

def remove_duplicate_letters(input_message):
    last_seen_indices = {}
    for index, character in enumerate(input_message):
        last_seen_indices[character] = index

    # We track visited characters to ensure each unique letter appears only once.
    visited_characters = set()
    selected_letter_stack = []

    for index, character in enumerate(input_message):
        if character not in visited_characters:
            # We pop larger characters to maintain alphabetical order if they appear later.
            while selected_letter_stack and selected_letter_stack[-1] > character and last_seen_indices[selected_letter_stack[-1]] > index:
                removed_character = selected_letter_stack.pop()
                visited_characters.remove(removed_character)

            selected_letter_stack.append(character)
            visited_characters.add(character)

    # The final string is assembled from our stack of optimally chosen letters.
    return "".join(selected_letter_stack)

Big(O) Analysis

Time Complexity
O(n) – To analyze the time complexity, let n be the length of the input message string. First, we iterate through the entire string once to record the frequency of each character. Then, we iterate through the string a second time to process each character, pushing and popping elements from our tracking stack at most once per character because each unique letter is added and removed from the pile a constant number of times. This bounds the total operations to a linear progression proportional to n, simplifying the overall runtime to O(n).
Space Complexity
O(1) – The auxiliary space is bound by the constant number of unique English letters in the alphabet. Specifically, the frequency map and the tracking pile store at most 26 elements regardless of the input string length N. Because the extra memory required does not grow with the size of the input, the space complexity simplifies to O(1).

Edge Cases

Empty string or single character string
How to Handle:
Return the input string directly as no duplicates can exist and order is already optimal.
String with all identical characters
How to Handle:
Keep only the first or last occurrence by utilizing a tracking mechanism that drops previous identical characters if a better lexicographical arrangement is found.
String with already unique characters in strictly increasing order
How to Handle:
Iterate through the string without removing any characters since the original order is already the lexicographically smallest.
String with unique characters in strictly decreasing order
How to Handle:
The monotonic stack mechanism will pop larger preceding characters in favor of smaller incoming characters, ultimately retaining only the final occurrence of each.
Characters appearing multiple times separated by other characters
How to Handle:
Use a last occurrence frequency map to ensure a character is only popped from the stack if it appears again later in the string.
Large input string approaching maximum constraints
How to Handle:
Process the string in a single linear pass using a stack and frequency array to achieve optimal O(N) time complexity.
Characters already present in the result stack
How to Handle:
Maintain a boolean visited set to immediately skip characters that have already been included in the final result.
0/25 completed