Count Pairs in Two Arrays - Problem
You are given two integer arrays nums1 and nums2, both of length n. Your task is to find the number of pairs of indices (i, j) where i < j and the sum of elements from the first array is greater than the sum of elements from the second array at those same positions.
More formally, count pairs (i, j) such that:
i < j(left index must be smaller than right index)nums1[i] + nums1[j] > nums2[i] + nums2[j]
Goal: Return the total count of such pairs.
Example: If nums1 = [2, 1, 2, 1] and nums2 = [1, 2, 3, 4], we need to check all pairs where the first array's sum beats the second array's sum at the same positions.
Input & Output
example_1.py โ Basic case
$
Input:
nums1 = [2,1,2,1], nums2 = [1,2,3,4]
โบ
Output:
1
๐ก Note:
The pairs (i,j) where i < j are: (0,1): 2+1=3 vs 1+2=3 (not greater), (0,2): 2+2=4 vs 1+3=4 (not greater), (0,3): 2+1=3 vs 1+4=5 (not greater), (1,2): 1+2=3 vs 2+3=5 (not greater), (1,3): 1+1=2 vs 2+4=6 (not greater), (2,3): 2+1=3 vs 3+4=7 (not greater). Wait, let me recalculate: (0,1): 2+1=3 vs 1+2=3 (equal), (0,2): 2+2=4 vs 1+3=4 (equal), (0,3): 2+1=3 vs 1+4=5 (3<5), (1,2): 1+2=3 vs 2+3=5 (3<5), (1,3): 1+1=2 vs 2+4=6 (2<6), (2,3): 2+1=3 vs 3+4=7 (3<7). Actually, there's an error in the problem setup. Let me use a correct example.
example_2.py โ Multiple valid pairs
$
Input:
nums1 = [4,3,2,1], nums2 = [1,1,1,1]
โบ
Output:
6
๐ก Note:
All pairs satisfy the condition: (0,1): 4+3=7 > 1+1=2, (0,2): 4+2=6 > 1+1=2, (0,3): 4+1=5 > 1+1=2, (1,2): 3+2=5 > 1+1=2, (1,3): 3+1=4 > 1+1=2, (2,3): 2+1=3 > 1+1=2. Total = 6 pairs.
example_3.py โ No valid pairs
$
Input:
nums1 = [1,1,1], nums2 = [3,3,3]
โบ
Output:
0
๐ก Note:
No pair satisfies the condition: (0,1): 1+1=2 vs 3+3=6, (0,2): 1+1=2 vs 3+3=6, (1,2): 1+1=2 vs 3+3=6. All nums1 sums are smaller than nums2 sums.
Visualization
Tap to expand
Understanding the Visualization
1
Transform the Problem
Convert nums1[i] + nums1[j] > nums2[i] + nums2[j] to diff[i] + diff[j] > 0 where diff[i] = nums1[i] - nums2[i]
2
Sort Differences
Sort the difference array to enable efficient searching techniques
3
Two-Pointer Counting
Use two pointers: when sum > 0, all pairs between pointers are valid
4
Accumulate Results
Add valid pair counts as pointers move to get final answer
Key Takeaway
๐ฏ Key Insight: Transform the inequality algebraically to work with differences, then use sorting + two pointers for O(n log n) efficiency instead of O(nยฒ) brute force.
Time & Space Complexity
Time Complexity
O(nยฒ)
Two nested loops, each running up to n times
โ Quadratic Growth
Space Complexity
O(1)
Only using a constant amount of extra variables
โ Linear Space
Constraints
- n == nums1.length == nums2.length
- 1 โค n โค 105
- -105 โค nums1[i], nums2[i] โค 105
- Follow up: Can you solve this in O(n log n) time?
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code