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: 0
💡 Note: With diff = -1, none of the pairs satisfy the inequality: (0,1): 1 ≤ 1 ✗, (0,2): -2 ≤ 1 ✗, (1,2): -3 ≤ 0 ✗
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 InequalityInput: nums1 = [3,2,5], nums2 = [2,1,1], diff = 1325nums1:211nums2:Check condition: nums1[i] - nums1[j] ≤ nums2[i] - nums2[j] + diffPair (0,1): 3-2 ≤ 2-1+1 → 1 ≤ 2 ✓Pair (0,2): 3-5 ≤ 2-1+1 → -2 ≤ 2 ✓Pair (1,2): 2-5 ≤ 1-1+1 → -3 ≤ 1 ✓Output: 3 valid pairs found
Understanding the Visualization
1
Input
Two arrays nums1, nums2 and difference value diff
2
Transform
Rearrange inequality to work with difference arrays
3
Count
Find number of valid pairs satisfying the condition
Key Takeaway
🎯 Key Insight: Transform the inequality algebraically to use efficient divide-and-conquer counting
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