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: 0
💡 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. Total: 0 valid pairs.
Example 2 — Clear Valid Pair
$ Input: nums1 = [3,4,1], nums2 = [1,1,2]
Output: 3
💡 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 in Two Arrays INPUT nums1: 2 1 3 1 i=0 i=1 i=2 i=3 nums2: 3 3 2 2 Condition: nums1[i] + nums1[j] > nums2[i] + nums2[j] Constraint: i < j n = 4 elements Find valid (i,j) pairs ALGORITHM STEPS 1 Transform Arrays diff[i] = nums1[i] - nums2[i] -1 -2 1 -1 2 Reframe Problem Find pairs: diff[i]+diff[j] > 0 3 Sort diff array [-2, -1, -1, 1] 4 Two Pointers left=0, right=n-1 -2 -1 -1 1 L R If sum > 0: count += R-L Move pointers inward FINAL RESULT Valid Pair Found: (i=0, j=2) 2 + 3 = 5 > 3 + 2 = 5 5 > 5? No... checking (i=2, j=3) in sorted -1 + 1 = 0 not > 0 Only 1 valid pair Output: 1 OK - 1 pair found Time: O(n log n) Space: O(n) Key Insight: Transform the condition nums1[i] + nums1[j] > nums2[i] + nums2[j] into (nums1[i] - nums2[i]) + (nums1[j] - nums2[j]) > 0. This creates a diff array where we count pairs with positive sum. Sorting + two pointers gives O(n log n) solution. TutorialsPoint - Count Pairs in Two Arrays | Optimal Solution
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