#3039
Apply Operations to Make String Empty
MediumArrayHash TableSortingCountingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach involves counting the frequency of each character and retaining only the last occurrence of the most frequent characters. This reduces unnecessary operations and improves efficiency.
⚙️
Algorithm
3 steps- 1Step 1: Count the frequency of each character in the string.
- 2Step 2: Identify the maximum frequency of any character.
- 3Step 3: Construct a new string containing only the last occurrences of characters that have the maximum frequency.
solution.py7 lines
1def apply_operations(s):
2 from collections import Counter
3 freq = Counter(s)
4 max_freq = max(freq.values())
5 last_occurrence = {c: i for i, c in enumerate(s) if freq[c] == max_freq}
6 result = ''.join(c for c in s if c in last_occurrence)
7 return resultℹ
Complexity note: The time complexity is O(n) because we only pass through the string a few times to count frequencies and build the result. The space complexity is O(n) due to the storage of character frequencies.
- 1Only the most frequent characters will remain before the last operation.
- 2The order of characters matters; we need to keep the last occurrence of each character.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.