- 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
- 51 lines of Python from the credited upstream file number-of-pairs-after-increment.py.
- The implementation visibly relies on sequence storage, hash 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 4import collections5 6 78class Solution(object):9 def numberOfPairs(self, nums1, nums2, queries):10 """11 :type nums1: List[int]12 :type nums2: List[int]13 :type queries: List[List[int]]14 :rtype: List[int]15 """16 def ceil_divide(a, b):17 return (a+b-1)b18 19 def update(cnt, left, right, val):20 for i in xrange(left, right+1):21 cnt[nums2[i]] -= 122 if not cnt[nums2[i]]:23 del cnt[nums2[i]]24 nums2[i] += val25 cnt[nums2[i]] += 126 27 cnt1 = collections.defaultdict(int)28 for x in nums1:29 cnt1[x] += 130 B = int((len(cnt1)*len(nums2))**0.5)+131 cnt2 = [collections.defaultdict(int) for _ in xrange(ceil_divide(len(nums2), B))]32 for i in xrange(len(cnt2)): 33 for j in xrange(i*B, min(i*B+B, len(nums2))):34 cnt2[i][nums2[j]] += 135 lazy = [0]*len(cnt2)36 result = []37 for q in queries:38 if q[0] == 2:39 tot = q[1]40 result.append(sum(cnt2[i][(tot-x)-lazy[i]]*c for x, c in cnt1.iteritems() for i in xrange(len(cnt2)) if (tot-x)-lazy[i] in cnt2[i]))41 continue42 x, y, val = q[1], q[2], q[3]43 if xB == yB:44 update(cnt2[xB], x, y, val)45 continue46 update(cnt2[xB], x, ((xB)+1)*B-1, val)47 for i in xrange((xB)+1, yB):48 lazy[i] += val49 update(cnt2[yB], (yB)*B, y, val)50 return result51