Count Pairs in Two Arrays Problem
#1885
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1885.
Given two integer arrays nums1 and nums2 of length n, count the pairs of indices (i, j) such that i < j and nums1[i] + nums1[j] > nums2[i] + nums2[j].
Return the number of pairs satisfying the condition.
Example 1:
Input: nums1 = [2,1,2,1], nums2 = [1,2,1,2]
Output: 1
Explanation: The pairs satisfying the condition are:
- (0, 2) where 2 + 2 > 1 + 1.
Example 2:
Input: nums1 = [1,10,6,2], nums2 = [1,4,1,5]
Output: 5
Explanation: The pairs satisfying the condition are:
- (0, 1) where 1 + 10 > 1 + 4.
- (0, 2) where 1 + 6 > 1 + 1.
- (1, 2) where 10 + 6 > 4 + 1.
- (1, 3) where 10 + 2 > 4 + 5.
- (2, 3) where 6 + 2 > 1 + 5.
Constraints:
n == nums1.length == nums2.length1 <= n <= 10^51 <= nums1[i], nums2[i] <= 10^5
Solution
Approach: Sorting + Two Pointers
Rewrite nums1[i] + nums1[j] > nums2[i] + nums2[j] as d[i] + d[j] > 0 with d[i] = nums1[i] - nums2[i]. The order of the indices no longer matters, so sort d and count pairs with a positive sum using two pointers l and r. If d[l] + d[r] <= 0, move l right. Otherwise every index from l to r - 1 pairs with r, which adds r - l pairs; then move r left.
Complexity: O(n log n) time, O(n) space.
class Solution:
def countPairs(self, nums1: List[int], nums2: List[int]) -> int:
nums = [a - b for a, b in zip(nums1, nums2)]
nums.sort()
l, r = 0, len(nums) - 1
ans = 0
while l < r:
while l < r and nums[l] + nums[r] <= 0:
l += 1
ans += r - l
r -= 1
return ans