Apply Operations to Make String Empty - Problem
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 iss = "abbca". - Remove the underlined characters
s = "abbca". 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".
Input & Output
Example 1 — Basic Case
$
Input:
s = "aabcbbca"
›
Output:
"ab"
💡 Note:
After round 1: remove first 'a', 'b', 'c' → "abbca". After round 2: remove first 'a', 'b', 'c' → "ba". After round 3: remove first 'a', 'b' → "". Return "ba" from before the last operation, but we need to reconsider... Actually, characters 'a' and 'b' both appear 3 times (max frequency), so they form the final non-empty string in order: "ab".
Example 2 — Single Character
$
Input:
s = "abcd"
›
Output:
""
💡 Note:
All characters appear once. After first round, all are removed and string becomes empty. The string before last operation is empty.
Example 3 — Repeated Pattern
$
Input:
s = "aaaa"
›
Output:
"a"
💡 Note:
Character 'a' appears 4 times. Each round removes one 'a', so we get: "aaaa" → "aaa" → "aa" → "a" → "". Return "a" from before the last operation.
Constraints
- 1 ≤ s.length ≤ 5 × 104
- s consists of lowercase English letters only
Visualization
Tap to expand
Understanding the Visualization
1
Input
Original string with character frequencies
2
Process
Find characters with maximum frequency
3
Output
String formed by max frequency characters
Key Takeaway
🎯 Key Insight: Characters with maximum frequency survive the longest and form the final non-empty string
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code