[LeetCode] Frequency Balance Subarray

3960. Frequency Balance Subarray

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 f such that every distinct value in the subarray occurs either f or 2 * f times, and both frequencies occur among the distinct values.

Return an integer denoting the length of the longest frequency balance subarray.

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
class Solution {
public:
int getLength(vector<int>& nums) {
int res = 0, n = nums.size();
auto update = [&](int x, unordered_map<int,int>& freq, unordered_map<int,int>& rfreq) {
if(freq[x]) {
if(--rfreq[freq[x]] == 0) rfreq.erase(freq[x]);
}
++freq[x];
rfreq[freq[x]]++;
};
for(int i = 0; i < n; i++) {
unordered_map<int,int> freq;
unordered_map<int,int> rfreq;
for(int j = i; j < n; j++) {
update(nums[j],freq,rfreq);
if(freq.size() == 1) {
res = max(res, j - i + 1);
} else if(rfreq.size() == 2) {
int a = 0, b = 0;
for(auto& [k,v] : rfreq) {
if(a) b = k;
else a = k;
}
if(a < b) swap(a,b);
if(a == b * 2) res = max(res, j - i + 1);
}

}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/frequency-balance-subarray/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.