Maximum Equal Frequency - Problem

Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences.

If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of occurrences (0).

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,2,1,1,5,3,3,5]
Output: 7
💡 Note: For prefix [2,2,1,1,5,3,3] of length 7, we can remove one occurrence of element 5, leaving frequencies: 2 appears 2 times, 1 appears 2 times, 3 appears 2 times - all equal
Example 2 — All Same Elements
$ Input: nums = [1,1,1,1]
Output: 4
💡 Note: All elements are the same, so we can remove any one element and all remaining elements have the same frequency (3)
Example 3 — Remove to Empty
$ Input: nums = [1]
Output: 1
💡 Note: Single element array - removing it leaves empty array where all elements have same frequency (0)

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 105

Visualization

Tap to expand
Maximum Equal Frequency Problem22115335Input: [2,2,1,1,5,3,3,5]Check Prefix [2,2,1,1,5,3,3]Frequencies: 2→2, 1→2, 5→1, 3→2Remove one 5: All frequencies = 2Valid prefix length: 7Check Full Array [2,2,1,1,5,3,3,5]Frequencies: 2→2, 1→2, 5→2, 3→2Remove any: Still have different frequenciesInvalid - cannot equalizeMaximum Valid Prefix Length: 7Answer: Remove one element from prefix to make all frequencies equal
Understanding the Visualization
1
Input Array
Array of positive integers with varying frequencies
2
Check Prefixes
For each prefix, determine if removing one element equalizes frequencies
3
Find Maximum
Return the length of the longest valid prefix
Key Takeaway
🎯 Key Insight: Identify mathematical patterns where removing one element equalizes all frequencies
Asked in
Google 25 Facebook 18
12.3K Views
Medium Frequency
~35 min Avg. Time
456 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