2426. Number of Pairs Satisfying Inequality
SourceBiweekly Contest 88 Q4DifficultyHardRating2030
Description
You are given two 0-indexed integer arrays nums1 and nums2, each of size n, and an integer diff. Find the number of pairs (i, j) such that:
0 <= i < j <= n - 1andnums1[i] - nums1[j] <= nums2[i] - nums2[j] + diff.
Return the number of pairs that satisfy the conditions.
Example 1:
Input: nums1 = [3,2,5], nums2 = [2,2,1], diff = 1 Output: 3 Explanation: There are 3 pairs that satisfy the conditions: 1. i = 0, j = 1: 3 - 2 <= 2 - 2 + 1. Since i < j and 1 <= 1, this pair satisfies the conditions. 2. i = 0, j = 2: 3 - 5 <= 2 - 1 + 1. Since i < j and -2 <= 2, this pair satisfies the conditions. 3. i = 1, j = 2: 2 - 5 <= 2 - 1 + 1. Since i < j and -3 <= 2, this pair satisfies the conditions. Therefore, we return 3.
Example 2:
Input: nums1 = [3,-1], nums2 = [-2,2], diff = -1 Output: 0 Explanation: Since there does not exist any pair that satisfies the conditions, we return 0.
Constraints:
n == nums1.length == nums2.length2 <= n <= 105-104 <= nums1[i], nums2[i] <= 104-104 <= diff <= 104
Solutions
Solution 1: Binary Indexed Tree
Thinking
The inequality \(nums1[i]-nums2[i]\le nums1[j]-nums2[j]+\textit{diff}\) for \(i<j\) cannot be double-looped at \(n\le 10^5\). With \(v=a-b\) we count prior \(v_i\le v_j+\textit{diff}\).
After a shift, a Fenwick tree stores seen \(v\). For each \(j\) from left to right, query the prefix up to \(v_j+\textit{diff}\), then insert \(v_j\).
We can transform the inequality in the problem to \(nums1[i] - nums2[i] \leq nums1[j] - nums2[j] + diff\). Therefore, if we calculate the difference between the corresponding elements of the two arrays and get another array \(nums\), the problem is transformed into finding the number of pairs in \(nums\) that satisfy \(nums[i] \leq nums[j] + diff\).
We can enumerate \(j\) from small to large, find out how many numbers before it satisfy \(nums[i] \leq nums[j] + diff\), and thus calculate the number of pairs. We can use a binary indexed tree to maintain the prefix sum, so we can find out how many numbers before it satisfy \(nums[i] \leq nums[j] + diff\) in \(O(\log n)\) time.
The time complexity is \(O(n \times \log n)\).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | |