#1224
Maximum Equal Frequency
HardArrayHash TableHash 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 solution leverages frequency counting and the properties of frequency distributions to determine the longest valid prefix in linear time. By tracking the frequency of numbers and their counts, we can efficiently check the conditions for equal frequency after removing one element.
⚙️
Algorithm
4 steps- 1Step 1: Initialize frequency maps to count occurrences of numbers and their frequencies.
- 2Step 2: Iterate through the array and update the frequency maps as you go.
- 3Step 3: For each prefix, check the conditions for valid frequency distributions using the frequency maps.
- 4Step 4: Update the maximum length of valid prefixes found.
solution.py26 lines
1# Full working Python code
2
3def maxEqualFreq(nums):
4 freq = {}
5 count = {}
6 max_length = 0
7 for i, num in enumerate(nums):
8 if num in freq:
9 count[freq[num]] -= 1
10 if count[freq[num]] == 0:
11 del count[freq[num]]
12 freq[num] += 1
13 else:
14 freq[num] = 1
15 count[freq[num]] = count.get(freq[num], 0) + 1
16 if len(count) == 1:
17 key = next(iter(count))
18 if key == 1 or count[key] == 1:
19 max_length = max(max_length, i + 1)
20 elif len(count) == 2:
21 keys = list(count.keys())
22 if (count[keys[0]] == 1 and (keys[0] - 1 == keys[1] or keys[0] == 1)) or
23 (count[keys[1]] == 1 and (keys[1] - 1 == keys[0] or keys[1] == 1))) :
24 max_length = max(max_length, i + 1)
25 return max_length
26ℹ
Complexity note: The time complexity is O(n) since we only traverse the array once while maintaining frequency counts. The space complexity is O(n) due to the storage of frequency maps.
- 1Understanding frequency distributions is crucial for this problem.
- 2The ability to efficiently update and check conditions on frequency maps can significantly reduce time complexity.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.