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 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".

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
Apply Operations to Make String EmptyInput String:a a b c b b c aCharacter Frequencies:a: 3 (max)b: 3 (max)c: 2Result (max frequency chars in order):a b
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
Asked in
Google 15 Amazon 12 Microsoft 8
23.4K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen