Maximum Equal Frequency - Problem
Maximum Equal Frequency is a challenging problem that tests your understanding of frequency analysis and edge case handling.

Given an array nums of positive integers, you need to find the longest possible prefix where removing exactly one element results in all remaining numbers having the same frequency.

Key Points:
• A prefix is a subarray starting from index 0
• You must remove exactly one element from the prefix
• After removal, all unique numbers must have equal occurrences
• If no elements remain after removal, it's considered valid (all have frequency 0)

Example: In array [2,2,1,1,5,3,3,5], the prefix [2,2,1,1,5] of length 5 works because removing one occurrence of any number (say 5) leaves us with frequencies: 2 appears twice, 1 appears twice - all equal!

Input & Output

example_1.py — Basic Case
$ Input: [2,2,1,1,5,3,3,5]
Output: 7
💡 Note: For prefix [2,2,1,1,5,3,3] of length 7, we have frequencies: 2 appears 2 times, 1 appears 2 times, 3 appears 2 times, 5 appears 1 time. Removing the single occurrence of 5 leaves all numbers with frequency 2.
example_2.py — All Same Frequency
$ Input: [1,1,2,2,3,3]
Output: 5
💡 Note: For prefix [1,1,2,2,3] of length 5, frequencies are: 1 appears 2 times, 2 appears 2 times, 3 appears 1 time. Removing one occurrence of 3 leaves frequencies [2,2], or removing one occurrence of 1 or 2 gives frequencies [1,2,1] which isn't equal. But removing the single 3 works.
example_3.py — Edge Case
$ Input: [1]
Output: 1
💡 Note: Array with single element. Removing it results in empty array where all elements (none) have equal frequency 0.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 105
  • The array contains only positive integers

Visualization

Tap to expand
Maximum Equal Frequency Solution22115Input Array: [2,2,1,1,5]Frequency Map2 → 2 times1 → 2 times5 → 1 timeTrack each element's frequencyFrequency Countfreq=1 → 1 numberfreq=2 → 2 numbersCount frequency distributionPattern Recognition✓ Pattern 3a: One frequency = 1Remove element with freq=1 (number 5)Result: Length = 5
Understanding the Visualization
1
Track Frequencies
Maintain count of how many times each number appears
2
Track Frequency Distribution
Count how many numbers have each frequency value
3
Check Valid Patterns
Recognize if current state matches any of the 5 valid patterns
4
Update Maximum
Keep track of the longest valid prefix found
Key Takeaway
🎯 Key Insight: Instead of trying all possible removals, recognize the 5 mathematical patterns where removing exactly one element creates equal frequencies. This reduces time complexity from O(n³) to O(n).
Asked in
Google 45 Facebook 32 Amazon 28 Microsoft 18
28.5K Views
Medium Frequency
~35 min Avg. Time
856 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