Taro Logo

Apply Operations to Make String Empty

#1 Most AskedMedium
0 views
Topics:
StringsArrays

You are given a string s.

Consider performing the following operation until s becomes empty:

  • For every alphabet character from 'a' to 'z', remove the first occurrence of that character in s (if it exists).

For example, let initially s = "aabcbbca". We do the following operations:

  • Remove the underlined characters s = "aabcbbca". The resulting string is s = "abbca".
  • Remove the underlined characters s = "abbca". The resulting string is s = "ba".
  • Remove the underlined characters s = "ba". The resulting string is s = "".

Return the value of the string s right before applying the last operation. In the example above, answer is "ba".

Example 1:

Input: s = "aabcbbca"
Output: "ba"
Explanation: Explained in the statement.

Example 2:

Input: s = "abcd"
Output: "abcd"
Explanation: We do the following operation:
- Remove the underlined characters s = "abcd". The resulting string is s = "".
The string just before the last operation is "abcd".

Constraints:

  • 1 <= s.length <= 5 * 105
  • s consists only of lowercase English 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 character set does the string `s` consist of? For example, are we dealing only with lowercase English letters, or could it include uppercase letters, digits, or Unicode characters?
  2. Can the input string `s` be empty, and if so, what should be returned in that case?
  3. When the operation removes the first occurrence of every distinct character, does the relative order of the remaining characters in the string need to be preserved in the final output?
  4. How should ties be handled if multiple characters appear the maximum number of times in the string?
  5. What should be the exact return type? Should the result be returned as a new string or an array of characters?

Brute Force Solution

Approach

Each step removes the first remaining copy of every letter that is still in the string. Repeating that until the string is empty leaves a last non-empty value, and that value is the answer.

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

  1. Copy the characters of the input into a list.
  2. Remember the current list as the last non-empty string.
  3. Drop the first remaining copy of each distinct letter.
  4. Repeat until the list is empty.
  5. Return the last non-empty string.

Code Implementation

def last_non_empty_string(text):
    # Each pass removes the first remaining copy of every letter still present.
    characters = list(text)
    last_non_empty = ""
    while characters:
        last_non_empty = "".join(characters)
        seen_letters = set()
        remaining_characters = []
        for character in characters:
            if character in seen_letters:
                remaining_characters.append(character)
            else:
                seen_letters.add(character)
        characters = remaining_characters
    return last_non_empty

Big(O) Analysis

Time Complexity
O(n^2) – Each pass scans the remaining characters, and a letter can survive at most n passes.
Space Complexity
O(n) – The character list holds the input and the letters that survive each pass.

Optimal Solution

Approach

Instead of repeatedly wiping away characters one by one, the optimal approach figures out which characters appear the most frequently and focuses only on the very last survivors. By counting how many times every character shows up, we can pinpoint exactly which ones will be erased in the final cleanup round.

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

  1. Count how many times every character appears throughout the entire text.
  2. Find the highest frequency belonging to any character in the text, since these will be the hardest ones to completely erase.
  3. Look for all the characters that share this maximum frequency, because they will be the absolute last ones standing when all operations finish.
  4. Pay attention to the order in which these most frequent characters make their final appearances near the end of the text.
  5. Collect these characters in that exact final order of appearance, ignoring all the characters that ran out earlier.
  6. Return this final collection of surviving characters as the answer.

Code Implementation

from collections import Counter

def last_non_empty_string(input_string):
    character_counts = Counter(input_string)

    # We identify the maximum frequency to find which characters survive until the very last operation round.
    maximum_frequency = max(character_counts.values())

    surviving_characters = set()
    for current_character, frequency in character_counts.items():
        if frequency == maximum_frequency:
            surviving_characters.add(current_character)

    final_survivors_list = []
    seen_survivors = set()

    # Traversing backwards ensures we capture the characters in their exact final order of appearance.
    for current_character in reversed(input_string):
        if current_character in surviving_characters and current_character not in seen_survivors:
            seen_survivors.add(current_character)
            final_survivors_list.append(current_character)

    final_survivors_list.reverse()

    # Reversing back restores the correct chronological sequence of the surviving characters.
    return "".join(final_survivors_list)

Big(O) Analysis

Time Complexity
O(n) – To analyze the time complexity, let n be the length of the string input. First, we iterate through the entire string of size n to count the frequency of each character using a hash map and track the maximum frequency. Second, we iterate through the unique characters or the string again to identify those matching the maximum frequency and record their last seen positions. Finally, we sort or collect these surviving characters based on their indices, which takes time proportional to the number of unique characters, bounded by the constant size of the alphabet. Thus, the total operations scale linearly as a single pass over n elements plus a minor constant overhead, simplifying directly to O(n).
Space Complexity
O(1) – To count character frequencies, we utilize a fixed-size frequency array or hash map limited to the 26 lowercase English letters. Similarly, storing the maximum frequency and the final surviving characters requires bounded extra memory that does not scale with the input string length. Since the number of possible unique characters is constant regardless of how large the input string N grows, the auxiliary space complexity remains strictly constant.

Edge Cases

String with all identical characters like aaaaa
How to Handle:
Counting frequencies and tracking maximum frequency naturally identifies the single surviving character set.
String where all characters have a frequency of one
How to Handle:
Since all characters appear equally and once, every character is removed in the final operation, leaving the original string or empty depending on exact problem ordering.
Maximum length constraints up to the problem limit
How to Handle:
A single linear pass to count frequencies ensures optimal O(N) time complexity and efficient memory scaling.
Characters with mixed varying frequencies
How to Handle:
Filtering by the absolute maximum frequency ensures only characters that persist until the very last operation are retained.
Preserving the original relative order of characters
How to Handle:
Iterating backwards through the string or referencing last seen positions ensures surviving characters appear in their correct relative sequence.
Alphabet containing only lowercase English letters
How to Handle:
Using a fixed-size frequency array of length 26 optimizes memory and lookup time compared to generic hash maps.
0/6 completed