Frequency Balance Subarray Problem
Description
LeetCode Problem 3960.
You are given an integer array nums.
Define a frequency balance subarray as follows:
- If the subarray contains only one distinct value, it is frequency balanced.
- Otherwise, there must exist a positive integer
fsuch that every distinct value in the subarray occurs eitherfor2 * ftimes, and both frequencies occur among the distinct values.
Return an integer denoting the length of the longest frequency balance subarray.
Example 1:
Input: nums = [1,2,2,1,2,3,3,3]
Output: 5
Explanation:
- The longest frequency balance subarray is [2, 1, 2, 3, 3].
- The elements that appear most frequently are 2 and 3, both appearing twice.
- The remaining element 1 appears once, meeting the requirements.
Example 2:
Input: nums = [5,5,5,5]
Output: 4
Explanation:
- The longest frequency balance subarray is [5, 5, 5, 5].
- The element that appears most frequently is 5.
- There are no other elements meeting the requirements.
Example 3:
Input: nums = [1,2,3,4]
Output: 1
Explanation:
Since all elements appear only once, the length of the longest frequency balance subarray is 1.
Constraints:
1 <= nums.length <= 10001 <= nums[i] <= 10^9
Solution
Approach: Enumeration + Hash Tables
Fix the left end l and extend the right end r one element at a time. Keep two hash tables for the current subarray: cnt (how many times each value occurs) and freq (how many distinct values have each occurrence count). Adding nums[r] moves one value from count c to c + 1, which updates freq in O(1).
The subarray is frequency balanced when either cnt has a single key, or freq has exactly two keys and one is twice the other. Since the count just updated is always a key of freq, it is enough to check whether 2 * c' or c' / 2 (for even c') is the other key. Record the longest such length.
Complexity: time O(n^2), space O(n).
class Solution:
def getLength(self, nums: List[int]) -> int:
n = len(nums)
ans = 1
for l in range(n):
cnt = Counter()
freq = Counter()
for r in range(l, n):
x = nums[r]
if freq[cnt[x]]:
freq[cnt[x]] -= 1
if freq[cnt[x]] == 0:
freq.pop(cnt[x])
cnt[x] += 1
freq[cnt[x]] += 1
if (len(cnt) == 1) or (
len(freq) == 2
and (freq[cnt[x] * 2] or (cnt[x] % 2 == 0 and freq[cnt[x] // 2]))
):
ans = max(ans, r - l + 1)
return ans