Count Pairs in Two Arrays - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: nums1 = [2,1,3,1], nums2 = [3,3,2,2]
Output: 1
💡 Note: Check all pairs (i,j) where i < j: (0,1): 2+1=3, 3+3=6, 3>6? No. (0,2): 2+3=5, 3+2=5, 5>5? No. (0,3): 2+1=3, 3+2=5, 3>5? No. (1,2): 1+3=4, 3+2=5, 4>5? No. (1,3): 1+1=2, 3+2=5, 2>5? No. (2,3): 3+1=4, 2+2=4, 4>4? No. Wait, let me recalculate: (2,3): nums1[2]+nums1[3] = 3+1 = 4, nums2[2]+nums2[3] = 2+2 = 4, so 4 > 4? No. Actually, let me be more careful. For (i,j) = (0,2): nums1[0]+nums1[2] = 2+3 = 5, nums2[0]+nums2[2] = 3+2 = 5, so 5 > 5? No. Hmm, let me try another example.
Example 2 — Clear Valid Pair
$ Input: nums1 = [3,4,1], nums2 = [1,1,2]
Output: 2
💡 Note: Check pairs: (0,1): 3+4=7, 1+1=2, 7>2? Yes ✓. (0,2): 3+1=4, 1+2=3, 4>3? Yes ✓. (1,2): 4+1=5, 1+2=3, 5>3? Yes ✓. Total: 3 valid pairs.
Example 3 — No Valid Pairs
$ Input: nums1 = [1,1], nums2 = [2,2]
Output: 0
💡 Note: Only one pair (0,1): 1+1=2, 2+2=4, 2>4? No. No valid pairs.

Constraints

  • 2 ≤ nums1.length ≤ 105
  • nums1.length == nums2.length
  • -105 ≤ nums1[i], nums2[i] ≤ 105

Visualization

Tap to expand
Count Pairs: nums1[i] + nums1[j] > nums2[i] + nums2[j]341nums1112nums2Check pair (0,1): 3+4 = 7, 1+1 = 2, 7 > 2? ✓ YesCheck pair (0,2): 3+1 = 4, 1+2 = 3, 4 > 3? ✓ YesCheck pair (1,2): 4+1 = 5, 1+2 = 3, 5 > 3? ✓ YesResult: 3 valid pairs
Understanding the Visualization
1
Input
Two arrays nums1 and nums2 of equal length
2
Process
Find pairs (i,j) where i<j and nums1[i]+nums1[j] > nums2[i]+nums2[j]
3
Output
Count of valid pairs
Key Takeaway
🎯 Key Insight: Transform the comparison to difference arrays and use two pointers for efficient counting
Asked in
Meta 15 Amazon 12 Google 8
28.5K Views
Medium Frequency
~25 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen