You are given a string s.
Consider performing the following operation until s becomes empty:
'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:
s = "aabcbbca". The resulting string is s = "abbca".s = "abbca". The resulting string is s = "ba".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 * 105s consists only 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:
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:
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
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:
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)
| Case | How to Handle |
|---|---|
| String with all identical characters like aaaaa | Counting frequencies and tracking maximum frequency naturally identifies the single surviving character set. |
| String where all characters have a frequency of one | 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 | A single linear pass to count frequencies ensures optimal O(N) time complexity and efficient memory scaling. |
| Characters with mixed varying frequencies | 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 | 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 | Using a fixed-size frequency array of length 26 optimizes memory and lookup time compared to generic hash maps. |