Skip to content

1885. Count Pairs in Two Arrays 👍

  • Time: $O(n\log n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  long long countPairs(vector<int>& nums1, vector<int>& nums2) {
    long long ans = 0;
    vector<int> A(nums1.size());

    for (int i = 0; i < A.size(); ++i)
      A[i] = nums1[i] - nums2[i];

    sort(begin(A), end(A));

    for (int i = 0; i < A.size(); ++i) {
      const auto it = lower_bound(begin(A) + i + 1, end(A), -A[i] + 1);
      ans += cend(A) - it;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
  public long countPairs(int[] nums1, int[] nums2) {
    long ans = 0;
    int[] A = new int[nums1.length]; // A[i] = nums1[i] - nums2[i]

    for (int i = 0; i < A.length; ++i)
      A[i] = nums1[i] - nums2[i];

    Arrays.sort(A);

    for (int i = 0; i < A.length; ++i) {
      final int index = firstGreater(A, -A[i]);
      ans += A.length - Math.max(i + 1, index);
    }

    return ans;
  }

  private int firstGreater(int[] A, int target) {
    int l = 0;
    int r = A.length;

    while (l < r) {
      final int m = (l + r) / 2;
      if (A[m] > target)
        r = m;
      else
        l = m + 1;
    }

    return l;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def countPairs(self, nums1: List[int], nums2: List[int]) -> int:
    ans = 0
    A = sorted([x - y for x, y in zip(nums1, nums2)])

    for i, a in enumerate(A):
      index = bisect_left(A, -a + 1)
      ans += len(A) - max(i + 1, index)

    return ans