- 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
- 67 lines of Python from the credited upstream file frequency-balance-subarray.py.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- No explicit 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(object):6 def getLength(self, nums):7 """8 :type nums: List[int]9 :rtype: int10 """11 val_to_idx = {x:i for i, x in enumerate(sorted(set(nums)))}12 arr = [val_to_idx[x] for x in nums]13 result = 014 for left in xrange(len(arr)):15 cnt, cnt2 = [0]*len(arr), [0]*(len(arr)+1)16 distinct = total = c = 017 for right in xrange(left, len(arr)):18 if cnt[arr[right]]:19 cnt2[cnt[arr[right]]] -= 120 if cnt2[cnt[arr[right]]] == 0:21 c -= 122 total -= cnt[arr[right]]23 cnt[arr[right]] += 124 if cnt[arr[right]] == 1:25 distinct += 126 cnt2[cnt[arr[right]]] += 127 if cnt2[cnt[arr[right]]] == 1:28 total += cnt[arr[right]]29 c += 130 if distinct == 1 or (c == 2 and total%3 == 0 and cnt2[total3]):31 result = max(result, right-left+1)32 return result33 34 353637import collections38 39 4041class Solution2(object):42 def getLength(self, nums):43 """44 :type nums: List[int]45 :rtype: int46 """47 result = 048 for left in xrange(len(nums)):49 cnt, cnt2 = collections.defaultdict(int), collections.defaultdict(int)50 distinct = total = c = 051 for right in xrange(left, len(nums)):52 if cnt[nums[right]]:53 cnt2[cnt[nums[right]]] -= 154 if cnt2[cnt[nums[right]]] == 0:55 c -= 156 total -= cnt[nums[right]]57 cnt[nums[right]] += 158 if cnt[nums[right]] == 1:59 distinct += 160 cnt2[cnt[nums[right]]] += 161 if cnt2[cnt[nums[right]]] == 1:62 total += cnt[nums[right]]63 c += 164 if distinct == 1 or (c == 2 and total%3 == 0 and cnt2[total3]):65 result = max(result, right-left+1)66 return result67