You are given two 0-indexed integer arrays nums1 and nums2, each of size n, and an integer diff. Find the number of pairs (i, j) such that:

  • 0 <= i < j <= n - 1 and
  • nums1[i] - nums1[j] <= nums2[i] - nums2[j] + diff.

Return the number of pairs that satisfy the conditions.

Input & Output

Example 1 — Basic Case
$ Input: nums1 = [3,2,5], nums2 = [2,1,1], diff = 1
Output: 3
💡 Note: Check all pairs: (0,1): 3-2 ≤ 2-1+1 → 1 ≤ 2 ✓, (0,2): 3-5 ≤ 2-1+1 → -2 ≤ 2 ✓, (1,2): 2-5 ≤ 1-1+1 → -3 ≤ 1 ✓. All 3 pairs satisfy the condition.
Example 2 — No Valid Pairs
$ Input: nums1 = [3,2,5], nums2 = [2,1,1], diff = -1
Output: 2
💡 Note: With diff = -1, check pairs: (0,1): 1 ≤ 0 ✗, (0,2): -2 ≤ 0 ✓, (1,2): -3 ≤ -1 ✓. Two pairs satisfy the condition.
Example 3 — Two Elements
$ Input: nums1 = [1,2], nums2 = [3,1], diff = 5
Output: 1
💡 Note: Only one pair (0,1): 1-2 ≤ 3-1+5 → -1 ≤ 7 ✓. The pair satisfies the condition.

Constraints

  • n == nums1.length == nums2.length
  • 1 ≤ n ≤ 105
  • -104 ≤ nums1[i], nums2[i] ≤ 104
  • -104 ≤ diff ≤ 104

Visualization

Tap to expand
Number of Pairs Satisfying Inequality INPUT nums1: 3 2 5 i: 0,1,2 nums2: 2 1 1 diff = 1 Condition: nums1[i]-nums1[j] <= nums2[i]-nums2[j]+diff Transform: arr[k] = nums1[k] - nums2[k] arr: 1 1 4 Find pairs: arr[i] <= arr[j] + diff ALGORITHM STEPS 1 Transform Arrays arr[i] = nums1[i] - nums2[i] 2 Merge Sort Divide Split array into halves 3 Count Cross Pairs Count where i in left, j in right 4 Merge and Sum Sum counts from all levels Merge Sort Tree [1,1,4] [1,1] [4] [1] [1] FINAL RESULT Valid Pairs Found: Pair (0,1): i=0, j=1 arr[0]=1 <= arr[1]+1=2 [OK] Pair (0,2): i=0, j=2 arr[0]=1 <= arr[2]+1=5 [OK] Pair (1,2): i=1, j=2 arr[1]=1 <= arr[2]+1=5 [OK] OUTPUT 3 3 pairs satisfy the inequality Key Insight: Transform the inequality: nums1[i] - nums1[j] <= nums2[i] - nums2[j] + diff becomes (nums1[i] - nums2[i]) <= (nums1[j] - nums2[j]) + diff, i.e., arr[i] <= arr[j] + diff. Use merge sort to count pairs efficiently in O(n log n) by counting during the merge step. TutorialsPoint - Number of Pairs Satisfying Inequality | Merge Sort with Counting Approach Time: O(n log n) | Space: O(n)
Asked in
Google 15 Microsoft 12 Facebook 8 Amazon 6
23.4K Views
Medium Frequency
~35 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