Skip to content

2426. Number of Pairs Satisfying Inequality 👍

  • 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
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class Solution {
 public:
  long long numberOfPairs(vector<int>& nums1, vector<int>& nums2, int diff) {
    // nums1[i] - nums1[j] <= nums2[i] - nums2[j] + diff
    // nums1[i] - nums2[i] <= nums1[j] - nums2[j] + diff
    // Define A[i] := nums1[i] - nums2[i] -> A[i] <= A[j] + diff
    vector<int> A;

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

    long ans = 0;
    mergeSort(A, 0, A.size() - 1, diff, ans);
    return ans;
  }

 private:
  void mergeSort(vector<int>& A, int l, int r, int diff, long& ans) {
    if (l >= r)
      return;

    const int m = (l + r) / 2;
    mergeSort(A, l, m, diff, ans);
    mergeSort(A, m + 1, r, diff, ans);
    merge(A, l, m, r, diff, ans);
  }

  void merge(vector<int>& A, int l, int m, int r, int diff, long& ans) {
    const int lo = m + 1;
    int hi = m + 1;  // the first index s.t. A[i] <= A[hi] + diff

    // For each index i in the range [l, m], add `r - hi + 1` to `ans`.
    for (int i = l; i <= m; ++i) {
      while (hi <= r && A[i] > A[hi] + diff)
        ++hi;
      ans += r - hi + 1;
    }

    vector<int> sorted(r - l + 1);
    int k = 0;      // sorted's index
    int i = l;      // left's index
    int j = m + 1;  // right's index

    while (i <= m && j <= r)
      if (A[i] < A[j])
        sorted[k++] = A[i++];
      else
        sorted[k++] = A[j++];

    // Put the possible remaining left part into the sorted array.
    while (i <= m)
      sorted[k++] = A[i++];

    // Put the possible remaining right part into the sorted array.
    while (j <= r)
      sorted[k++] = A[j++];

    copy(sorted.begin(), sorted.end(), A.begin() + l);
  }
};