Count Valid Pairs with Mathematical Constraint

You are given two integer arrays nums1 and nums2, each of size n, and an integer diff. Your task is to find how many pairs of indices (i, j) satisfy a specific mathematical relationship.

A pair (i, j) is considered valid if:
0 ≤ i < j ≤ n - 1 (i must come before j)
nums1[i] - nums1[j] ≤ nums2[i] - nums2[j] + diff

The challenge lies in efficiently counting these pairs without checking every possible combination, as that would be too slow for large arrays.

Example: If nums1 = [3,2,5], nums2 = [2,5,1], and diff = 2, we need to check pairs (0,1), (0,2), and (1,2) against our inequality constraint.

Input & Output

example_1.py — Basic Case
$ Input: nums1 = [3,2,5], nums2 = [2,5,1], diff = 2
Output: 2
💡 Note: We check pairs (0,1), (0,2), and (1,2). For (0,2): 3-5 ≤ 2-1+2 → -2 ≤ 3 ✓. For (1,2): 2-5 ≤ 5-1+2 → -3 ≤ 6 ✓. Two pairs satisfy the condition.
example_2.py — All Valid
$ Input: nums1 = [3,2,5], nums2 = [2,2,2], diff = 1
Output: 3
💡 Note: With nums2 constant, the inequality becomes nums1[i] - nums1[j] ≤ 1. All three pairs (0,1), (0,2), and (1,2) satisfy this condition since differences are small.
example_3.py — Edge Case
$ Input: nums1 = [3,2], nums2 = [1,1], diff = -1
Output: 0
💡 Note: Only one pair (0,1) to check: 3-2 ≤ 1-1+(-1) → 1 ≤ -1, which is false. With negative diff, the constraint becomes very strict.

Constraints

  • n == nums1.length == nums2.length
  • 1 ≤ n ≤ 105
  • -104 ≤ nums1[i], nums2[i] ≤ 104
  • -104 ≤ diff ≤ 104
  • Time limit: 2 seconds for all test cases

Visualization

Tap to expand
Problem TransformationOriginal Inequality:nums1[i] - nums1[j] ≤ nums2[i] - nums2[j] + diffRearrange:nums1[i] - nums2[i] ≤ nums1[j] - nums2[j] + diffTransform:Let arr[i] = nums1[i] - nums2[i]Final Problem:Count pairs (i,j) where i < j and arr[i] ≤ arr[j] + diff
Understanding the Visualization
1
Original Problem
Count pairs (i,j) where nums1[i] - nums1[j] ≤ nums2[i] - nums2[j] + diff
2
Rearrange Terms
Move nums2 terms: nums1[i] - nums2[i] ≤ nums1[j] - nums2[j] + diff
3
Transform Arrays
Create arr[i] = nums1[i] - nums2[i] for all indices
4
Simplified Problem
Count pairs where arr[i] ≤ arr[j] + diff with i < j
Key Takeaway
🎯 Key Insight: Mathematical transformation reduces a complex 2-array problem to a simpler 1-array inversion counting problem!
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
31.5K Views
Medium-High Frequency
~25 min Avg. Time
890 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