1224. Maximum Equal Frequency
Description
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 ocurrences (0).
Example 1:
Input: nums = [2,2,1,1,5,3,3,5] Output: 7 Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4] = 5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice.
Example 2:
Input: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5] Output: 13
Constraints:
2 <= nums.length <= 1051 <= nums[i] <= 105
Solutions
Solution 1: Array or Hash Table
Thinking
We need the longest prefix from which deleting one element equalizes remaining frequencies. \(n \le 10^5\), so we cannot recount every prefix.
Keep value frequencies \(cnt\), the frequency-of-frequencies \(ccnt\), and the maximum frequency \(mx\). A prefix works iff all frequencies are \(1\); or they are only \(mx\) and \(mx-1\) with a unique value at \(mx\); or all are \(mx\) except one singleton.
We update both maps left to right and test the three shapes in \(O(1)\) from \(ccnt\) and \(mx\), recording the largest valid index.
We use \(cnt\) to record the number of times each element \(v\) appears in \(nums\), and \(ccnt\) to record the number of times each count appears. The maximum number of times an element appears is represented by \(mx\).
While traversing \(nums\):
- If the maximum count \(mx=1\), it means that each number in the current prefix appears \(1\) time. If we delete any one of them, the remaining numbers will all have the same count.
- If all numbers appear \(mx\) and \(mx-1\) times, and only one number appears \(mx\) times, then we can delete one occurrence of the number that appears \(mx\) times. The remaining numbers will all have a count of \(mx-1\), which meets the condition.
- If, except for one number, all other numbers appear \(mx\) times, then we can delete the number that appears once. The remaining numbers will all have a count of \(mx\), which meets the condition.
The time complexity is \(O(n)\), and the space complexity is \(O(n)\). Here, \(n\) is the length of the \(nums\) array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | |