- Choose the aggregate stored for each interval or prefix.
- Build or initialize the structure from the input.
- Apply updates and combine the affected nodes to answer each query.
Code notes
- 109 lines of Python from the credited upstream file number-of-pairs-satisfying-inequality.py.
- The implementation visibly relies on sequence storage, ordered lookup.
- No explicit loop blocks detected.
Complexity
Count the build once, then multiply the logarithmic update or query path by the number of operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4from sortedcontainers import SortedList5import itertools6 7 89class Solution(object):10 def numberOfPairs(self, nums1, nums2, diff):11 """12 :type nums1: List[int]13 :type nums2: List[int]14 :type diff: int15 :rtype: int16 """17 sl = SortedList()18 result = 019 for x, y in itertools.izip(nums1, nums2):20 result += sl.bisect_right((x-y)+diff)21 sl.add(x-y)22 return result23 24 252627import itertools28import bisect29 30 31class BIT(object): 32 def __init__(self, n):33 self.__bit = [0]*(n+1) 34 35 def add(self, i, val):36 i += 1 37 while i < len(self.__bit):38 self.__bit[i] += val39 i += (i & -i)40 41 def query(self, i):42 i += 1 43 ret = 044 while i > 0:45 ret += self.__bit[i]46 i -= (i & -i)47 return ret48 49 5051class Solution2(object):52 def numberOfPairs(self, nums1, nums2, diff):53 """54 :type nums1: List[int]55 :type nums2: List[int]56 :type diff: int57 :rtype: int58 """59 sorted_nums = sorted(set(x-y for x, y in itertools.izip(nums1, nums2)))60 num_to_idx = {x:i for i, x in enumerate(sorted_nums)}61 result = 062 bit = BIT(len(num_to_idx))63 for x, y in itertools.izip(nums1, nums2):64 result += bit.query(bisect.bisect_right(sorted_nums, (x-y)+diff)-1)65 bit.add(num_to_idx[x-y], 1)66 return result67 68 697071import itertools72 73 7475class Solution3(object):76 def numberOfPairs(self, nums1, nums2, diff):77 """78 :type nums1: List[int]79 :type nums2: List[int]80 :type diff: int81 :rtype: int82 """83 def merge_sort(nums, left, right, result):84 if left == right:85 return86 mid = left+(right-left)287 merge_sort(nums, left, mid, result)88 merge_sort(nums, mid+1, right, result)89 r = mid+190 for l in xrange(left, mid+1):91 while r < right+1 and nums[l]-nums[r] > diff:92 r += 193 result[0] += right-r+194 tmp = []95 l, r = left, mid+196 while l < mid+1 or r < right+1:97 if r >= right+1 or (l < mid+1 and nums[l] <= nums[r]):98 tmp.append(nums[l])99 l += 1100 else:101 tmp.append(nums[r])102 r += 1103 nums[left:right+1] = tmp104 105 nums = [x-y for x, y in itertools.izip(nums1, nums2)]106 result = [0]107 merge_sort(nums, 0, len(nums)-1, result)108 return result[0]109