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 INPUT nums array: 2 i=0 2 i=1 1 i=2 1 i=3 5 i=4 3 i=5 3 i=6 5 i=7 Track Frequencies: count[num] = freq 2:2, 1:2, 5:1, 3:2 freq[cnt] = howMany 1:1, 2:3 Track maxFreq: maxFreq = 2 Goal: Find longest prefix where removing 1 element equalizes all frequencies ALGORITHM STEPS 1 Initialize Maps count[num], freq[cnt] maxFreq = 0 2 Iterate + Update For each num: update count, freq, maxFreq 3 Check Valid Cases At each position, check if prefix is valid 4 Valid Conditions a) maxF*cnt == i+1 all same freq, remove 1 b) (maxF-1)*cnt+1 == i+1 one has extra, remove it c) maxF+(maxF-1)*rest one unique at maxF d) cnt*(maxF+1) == i+1 FINAL RESULT Longest Valid Prefix: 2 2 1 1 5 3 3 Remove 5 (one occurrence): 2: 2 times 1: 2 times 3: 2 times Output: 7 OK - All frequencies = 2 after removing one 5 Length 8 invalid: Can't equalize with 1 removal Key Insight: Track both count[num] (frequency of each number) and freq[cnt] (how many numbers have count c). At each index, check if removing exactly one element can make all remaining frequencies equal. Four valid cases: all freq=1, one extra occurrence, all maxFreq with one unique, or one less occurrence. TutorialsPoint - Maximum Equal Frequency | Optimal Solution O(n)
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