Apply Operations to Make String Empty - Problem

You are given a string s. Your task is to repeatedly apply a special operation until the string becomes empty, then return the string right before the final operation.

The Operation: In each round, scan through the alphabet from 'a' to 'z' and remove the first occurrence of each letter that exists in the current string.

Example walkthrough:

  • Initial: s = "aabcbbca"
  • Round 1: Remove first 'a', first 'b', first 'c' → "abbca"
  • Round 2: Remove first 'a', first 'b', first 'c' → "ba"
  • Round 3: Remove first 'a', first 'b' → "" (empty)
  • Answer: "ba" (string before the final operation)

This problem tests your ability to simulate operations efficiently and understand when to stop the process.

Input & Output

example_1.py — Standard Case
$ Input: "aabcbbca"
Output: "ba"
💡 Note: Round 1: Remove first 'a', 'b', 'c' → 'abbca'. Round 2: Remove first 'a', 'b', 'c' → 'ba'. Round 3: Remove 'a', 'b' → empty. Answer is 'ba' (before final round).
example_2.py — Single Character Types
$ Input: "abcdef"
Output: ""
💡 Note: Round 1: Remove 'a', 'b', 'c', 'd', 'e', 'f' → empty string. Since it becomes empty in one round, return empty string.
example_3.py — Multiple Same Characters
$ Input: "aaaa"
Output: "a"
💡 Note: Round 1: Remove first 'a' → 'aaa'. Round 2: Remove first 'a' → 'aa'. Round 3: Remove first 'a' → 'a'. Round 4: Remove 'a' → empty. Answer is 'a'.

Visualization

Tap to expand
📚 Library Book Return ProcessInitial Stack of Books:AABCBBCADay 1 - Remove first A, B, C:ABBCARemaining: A B B C ADay 2 - Remove first A, B, C:BARemaining: B A← This is our answer!Day 3 - Remove A, B:Stack becomes empty💡 Answer: "ba" (the state before the final empty)
Understanding the Visualization
1
Day 1 Setup
Books arranged: A A B C B B C A
2
Day 1 Collection
Collect first A, first B, first C → Remaining: A B B C A
3
Day 2 Collection
Collect first A, first B, first C → Remaining: B A
4
Day 3 Collection
Collect A and B → Empty pile
5
Answer
The day before the pile became empty, we had: B A
Key Takeaway
🎯 Key Insight: Each character's survival depends on how many identical characters come before it in the original string. We need the second-to-last non-empty state!

Time & Space Complexity

Time Complexity
⏱️
O(n)

Single pass to count frequencies and another pass to build result

n
2n
Linear Growth
Space Complexity
O(1)

Only need constant space for character counting (at most 26 characters)

n
2n
Linear Space

Constraints

  • 1 ≤ s.length ≤ 105
  • s consists of only lowercase English letters
  • The string will always become empty after finite operations
Asked in
Google 45 Meta 38 Amazon 32 Microsoft 28
43.5K Views
Medium-High Frequency
~18 min Avg. Time
1.8K 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