- 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
- 62 lines of Python from the credited upstream file sum-of-weighted-modes-in-subarrays.py.
- The implementation visibly relies on sequence storage, hash lookup, work queue.
- 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 4import collections5from sortedcontainers import SortedList6 7 89class Solution(object):10 def modeWeight(self, nums, k):11 """12 :type nums: List[int]13 :type k: int14 :rtype: int15 """16 def add(x, diff):17 if cnt[x]:18 sl.remove((-cnt[x], x))19 cnt[x] += diff20 if cnt[x]:21 sl.add((-cnt[x], x))22 else:23 del cnt[x]24 25 cnt = collections.defaultdict(int)26 sl = SortedList()27 result = 028 for i in xrange(len(nums)):29 add(nums[i], +1)30 if i >= k-1:31 result += -sl[0][0]*sl[0][1]32 add(nums[i-k+1], -1)33 return result34 35 363738import collections39import heapq40 41 4243class Solution2(object):44 def modeWeight(self, nums, k):45 """46 :type nums: List[int]47 :type k: int48 :rtype: int49 """50 cnt = collections.defaultdict(int)51 max_heap = []52 result = 053 for i in xrange(len(nums)):54 cnt[nums[i]] += 155 heapq.heappush(max_heap, (-cnt[nums[i]], nums[i]))56 if i >= k-1:57 while -max_heap[0][0] != cnt[max_heap[0][1]]:58 heapq.heappop(max_heap)59 result += -max_heap[0][0]*max_heap[0][1]60 cnt[nums[i-k+1]] -= 161 return result62