- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 78 lines of C++ from the credited upstream file frequency-balance-subarray.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 6 loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution {6public:7 int getLength(vector<int>& nums) {8 vector<int> sorted_vals(nums);9 ranges::sort(sorted_vals);10 sorted_vals.erase(unique(begin(sorted_vals), end(sorted_vals)), end(sorted_vals));11 unordered_map<int, int> val_to_idx;12 for (int i = 0; i < size(sorted_vals); ++i) {13 val_to_idx[sorted_vals[i]] = i;14 }15 vector<int> arr(size(nums));16 for (int i = 0; i < size(nums); ++i) {17 arr[i] = val_to_idx[nums[i]];18 }19 int result = 0;20 for (int left = 0; left < size(arr); ++left) {21 vector<int> cnt(size(arr)), cnt2(size(arr) + 1);22 int distinct = 0, total = 0, c = 0;23 for (int right = left; right < size(arr); ++right) {24 if (cnt[arr[right]]) {25 if (--cnt2[cnt[arr[right]]] == 0) {26 --c;27 total -= cnt[arr[right]];28 }29 }30 if (++cnt[arr[right]] == 1) {31 ++distinct;32 }33 if (++cnt2[cnt[arr[right]]] == 1) {34 total += cnt[arr[right]];35 ++c;36 }37 if (distinct == 1 || (c == 2 && total % 3 == 0 && cnt2[total / 3])) {38 result = max(result, right - left + 1);39 }40 }41 }42 return result;43 }44};45 46474849class Solution2 {50public:51 int getLength(vector<int>& nums) {52 int result = 0;53 for (int left = 0; left < size(nums); ++left) {54 unordered_map<int, int> cnt, cnt2;55 int distinct = 0, total = 0, c = 0;56 for (int right = left; right < size(nums); ++right) {57 if (cnt[nums[right]]) {58 if (--cnt2[cnt[nums[right]]] == 0) {59 --c;60 total -= cnt[nums[right]];61 }62 }63 if (++cnt[nums[right]] == 1) {64 ++distinct;65 }66 if (++cnt2[cnt[nums[right]]] == 1) {67 total += cnt[nums[right]];68 ++c;69 }70 if (distinct == 1 || (c == 2 && total % 3 == 0 && cnt2[total / 3])) {71 result = max(result, right - left + 1);72 }73 }74 }75 return result;76 }77};78