Apply Operations to Make String Empty Problem
Description
LeetCode Problem 3039.
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 ins(if it exists).
For example, let initially s = "aabcbbca". We do the following operations:
- Remove the underlined characters
s = "**a**a**bc**bbca". The resulting string iss = "abbca". - Remove the underlined characters
s = "**ab**b**c**a". The resulting string iss = "ba". - Remove the underlined characters
s = "**ba**". The resulting string iss = "".
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 * 10^5sconsists only of lowercase English letters.
Solution
Approach: Counting
Every round removes one copy of each letter that is still present, so a letter occurring c times survives for exactly c rounds. The last round therefore involves the letters with the maximum count mx, and what is left before it is one copy of each such letter.
Which copy remains? Always the last one, since the first occurrence is removed each round. So count each letter and record its last position, then scan s and keep the characters whose count is mx and whose index is that letter's last position. This keeps them in their original order.
Complexity: time O(n), space O(26).
class Solution:
def lastNonEmptyString(self, s: str) -> str:
cnt = Counter(s)
mx = cnt.most_common(1)[0][1]
last = {c: i for i, c in enumerate(s)}
return "".join(c for i, c in enumerate(s) if cnt[c] == mx and last[c] == i)