Taro Logo

Lexicographically Smallest String After Deleting Duplicate Characters

Hard
Asked by:
Paytm
0 views
Topics:
StringsGreedy AlgorithmsStacks

You are given a string s that consists of lowercase English letters.

You can perform the following operation any number of times (possibly zero times):

  • Choose any letter that appears at least twice in the current string s and delete any one occurrence.

Return the lexicographically smallest resulting string that can be formed this way.

Example 1:

Input: s = "aaccb"

Output: "aacb"

Explanation:

We can form the strings "acb", "aacb", "accb", and "aaccb". "aacb" is the lexicographically smallest one.

For example, we can obtain "aacb" by choosing 'c' and deleting its first occurrence.

Example 2:

Input: s = "z"

Output: "z"

Explanation:

We cannot perform any operations. The only string we can form is "z".

Constraints:

  • 1 <= s.length <= 105
  • s contains lowercase English letters only.

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? Should I assume it only contains lowercase English letters, or could it include uppercase letters, digits, and special characters?
  2. What should be returned if the input string is empty or null?
  3. Could you clarify the requirement to 'remove duplicate characters'—does this mean every unique character should appear exactly once in the final result, or are we removing duplicates only when we choose to based on the lexicographical criteria (similar to LeetCode 316 / 1081)?
  4. Regarding the relative order, does the problem imply that the relative order of the remaining characters must be strictly preserved from their original appearance in s?
  5. Is the input string guaranteed to fit entirely in memory, or should I be concerned about extremely large strings?

Brute Force Solution

Approach

This search deletes one extra copy of a letter at a time and remembers every string it can reach. A deletion is allowed only while that letter still appears at least twice. The smallest string visited is the answer, and the search grows quickly because each string branches into many shorter ones.

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

  1. Start from the original string and treat it as the best answer so far.
  2. Count the letters in the current string.
  3. Delete one occurrence of any letter that still appears at least twice.
  4. Keep the candidate when it is lexicographically smaller than the best string.
  5. Repeat from every new string until no further deletion is possible.
  6. Return the smallest string found.

Code Implementation

def lexicographically_smallest_string(text):
    # Every reachable string comes from deleting one extra copy at a time.
    best_string = text
    seen_strings = {text}
    pending_strings = [text]
    while pending_strings:
        current_string = pending_strings.pop()
        letter_counts = {}
        for character in current_string:
            letter_counts[character] = letter_counts.get(character, 0) + 1
        for index, character in enumerate(current_string):
            if letter_counts[character] < 2:
                continue
            # This copy can go because the letter still appears somewhere else.
            candidate = current_string[:index] + current_string[index + 1 :]
            if candidate in seen_strings:
                continue
            seen_strings.add(candidate)
            if candidate < best_string:
                best_string = candidate
            pending_strings.append(candidate)
    return best_string

Big(O) Analysis

Time Complexity
O(n * 2^n) – Each character can be kept or deleted, and every reachable string is expanded by scanning its characters.
Space Complexity
O(n * 2^n) – The search stores every reachable string so the same deletion path is not explored twice.

Optimal Solution

Approach

Every letter that appears in the input has to stay at least once, and an extra copy can be deleted while another copy remains. The scan keeps a stack and drops a larger letter when a smaller letter arrives and a spare copy of the larger letter still exists. Leftover copies at the end are removed when they cannot make the result smaller.

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

  1. Count how many times each letter appears.
  2. Walk the string from left to right and push each letter onto a stack.
  3. Pop a larger letter when the current letter is smaller and a spare copy of the larger letter remains.
  4. After the scan, pop trailing letters that still have a spare copy.
  5. Join the stack into the answer.

Code Implementation

def lexicographically_smallest_string(text):
    # Spare copies are what make a deletion legal, so count every letter first.
    letter_counts = {}
    for character in text:
        letter_counts[character] = letter_counts.get(character, 0) + 1

    kept_characters = []
    for character in text:
        # Drop a larger letter when a smaller one arrives and a spare copy remains.
        while (
            kept_characters
            and kept_characters[-1] > character
            and letter_counts[kept_characters[-1]] > 1
        ):
            removed_character = kept_characters.pop()
            letter_counts[removed_character] -= 1
        kept_characters.append(character)

    # Copies left on the end cannot help, so trim them while a spare remains.
    while kept_characters and letter_counts[kept_characters[-1]] > 1:
        removed_character = kept_characters.pop()
        letter_counts[removed_character] -= 1
    return "".join(kept_characters)

Big(O) Analysis

Time Complexity
O(n) – Each character is pushed once and popped at most once, so the scan is linear in the length of the string.
Space Complexity
O(n) – The stack and the letter counts together hold one entry per character.

Edge Cases

Empty string or single character string
How to Handle:
Return the input string directly as no duplicates can exist or need removal.
String with all identical characters
How to Handle:
Greedy stack approach keeps only the last occurrence of the character to ensure minimal length and valid order.
String already in strictly increasing lexicographical order
How to Handle:
The algorithm processes the characters and returns the original string without unnecessary removals.
String in strictly decreasing lexicographical order with duplicates
How to Handle:
Frequency tracking and stack pops remove earlier larger characters, retaining only the final instance of each character.
Maximum length constraints up to the problem limit
How to Handle:
Using a linear time stack and frequency array approach ensures optimal O(N) time and space complexity without scaling issues.
Characters with alternating frequencies and values
How to Handle:
Monotonic stack checks character availability using a remaining frequency map to safely pop larger elements when smaller ones can appear later.
String containing special characters or mixed cases
How to Handle:
Standard ASCII values dictate lexicographical comparisons natively, allowing the same logic to apply without modification.
Duplicate characters scattered far apart
How to Handle:
A frequency count array tracks remaining occurrences globally so earlier characters are only popped if more are guaranteed to follow.