This problem asks us to count the number of pairs of indices (i, j) where i < j and nums1[i] + nums1[j] > nums2[i] + nums2[j]. The most efficient approach leverages sorting and a two-pointer technique.
1. Transformation:
The core inequality, nums1[i] + nums1[j] > nums2[i] + nums2[j]
, can be rewritten as:
nums1[i] - nums2[i] + nums1[j] - nums2[j] > 0
Let's define a new array diff
where diff[i] = nums1[i] - nums2[i]
. Now the inequality becomes:
diff[i] + diff[j] > 0
This simplification is crucial for the efficiency of the algorithm.
2. Sorting:
We sort the diff
array. This allows us to efficiently find pairs that satisfy the condition using two pointers.
3. Two-Pointer Approach:
Initialize two pointers: left
(pointing to the beginning of the sorted diff
array) and right
(pointing to the end).
Iterate: The core logic lies in the while loop (while (left < right)
).
Inner Loop: The inner while
loop (while (left < right && diff[left] + diff[right] <= 0)
) efficiently skips pairs that don't satisfy the condition. If the sum is less than or equal to 0, it means that any pair with diff[left]
will also fail to satisfy the inequality with any element greater than diff[right]
(because the array is sorted). Thus we increment left
.
Counting Pairs: Once we find a pair where diff[left] + diff[right] > 0
, we know that all pairs (diff[left]
with diff[left+1]
, diff[left+2]
, ..., diff[right]
) satisfy the condition. The number of such pairs is right - left
. We add this count to our result.
Pointer Movement: After counting the pairs, we decrement right
to consider pairs with a smaller element at the right pointer.
4. Time and Space Complexity:
diff
array. In-place sorting algorithms could reduce this space slightly depending on the implementation.Code Examples (Python):
def countPairs(nums1: list[int], nums2: list[int]) -> int:
diff = [nums1[i] - nums2[i] for i in range(len(nums1))]
diff.sort()
left, right = 0, len(diff) - 1
count = 0
while left < right:
while left < right and diff[left] + diff[right] <= 0:
left += 1
count += right - left
right -= 1
return count
The code in other languages (Java, C++, Go, TypeScript, Rust, JavaScript) follows the same algorithmic structure, only differing in syntax and specific library functions used for sorting and array manipulation. The time and space complexity remain the same across all implementations.