Count Pairs in Two Arrays

Transform to nums1[i] - nums2[i], sort, and count pairs whose sum exceeds zero with two pointers.

Medium
Time O(n log n) Space O(n)
LeetCode
3 min read
two-pointers sorting math

Problem#

Given equal-length arrays nums1 and nums2, count pairs (i, j) with i < j such that nums1[i] + nums1[j] > nums2[i] + nums2[j].

Examples#

  • nums1 = [2,1,2,1], nums2 = [1,2,1,2]1
  • nums1 = [1,10,6,2], nums2 = [1,4,1,5]5

Constraints#

  • n == nums1.length == nums2.length, 1 <= n <= 10^5, 1 <= nums1[i], nums2[i] <= 10^5.

Approach#

Define d[i] = nums1[i] - nums2[i]. The inequality becomes d[i] + d[j] > 0. Sort d and use two pointers: if the sum is positive, every index between contributes.

Solution#

Count Pairs in Two Arrays
class Solution {
public:
long long countPairs(vector<int>& nums1, vector<int>& nums2) {
int n = nums1.size();
vector<int> d(n);
for (int i = 0; i < n; ++i) d[i] = nums1[i] - nums2[i];
sort(d.begin(), d.end());
long long ans = 0;
int l = 0, r = n - 1;
while (l < r) {
if (d[l] + d[r] > 0) {
ans += r - l;
--r;
} else {
++l;
}
}
return ans;
}
};

Editorial#

Rewriting the constraint as a one-dimensional condition on d[i] + d[j] removes the dependence on index pairing — order no longer matters because we just need any valid combination. Sorting plus two pointers counts valid pairs in O(n) after the sort.

Complexity#

  • Time: O(n log n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.