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: "ba"
💡 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.
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 Empty INPUT String s = "aabcbbca" a a b c b b c a 0 1 2 3 4 5 6 7 Character Frequency Char a b Count 2 3 Char c Count 2 Max frequency = 3 (for 'b') Total operations = 3 ALGORITHM STEPS 1 Count Frequencies Count each char: a=2, b=3, c=2 2 Find Max Frequency maxFreq = 3 (char 'b') 3 Find Last Occurrence Track last index of max chars 4 Build Result Keep chars with maxFreq only Operations Simulation Op 1: aabcbbca --> abba Op 2: abba --> ab Op 3: ab --> "" Before last op: "ab" FINAL RESULT String before last operation: a b Output: "ab" Why "ab"? - 'b' appears most (3 times) - 'a' has same max freq: NO - Keep chars with maxFreq - Last 'a' at idx 7, 'b' at idx 5 - Result: chars before empty OK - DONE Key Insight: The answer contains only characters with maximum frequency. Before the last operation, we keep the last occurrences of all max-frequency characters in their original order. Time: O(n), Space: O(1) - Only need frequency count and track last positions. TutorialsPoint - Apply Operations to Make String Empty | Optimal Solution
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