Leetcode #2426: Number of Pairs Satisfying Inequality
In this guide, we solve Leetcode #2426 Number of Pairs Satisfying Inequality in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Binary Indexed Tree, Segment Tree, Array, Binary Search, Divide and Conquer, Ordered Set, Merge Sort
Intuition
The problem structure suggests a monotonic decision, which makes binary search a natural fit.
By halving the search space each step, we reach the answer efficiently.
Approach
Search either directly on a sorted array or on the answer space using a check function.
Each check is fast, and the logarithmic search keeps the overall runtime low.
Steps:
- Define the search bounds.
- Check the mid point condition.
- Narrow the bounds until convergence.
Example
Input: nums1 = [3,2,5], nums2 = [2,2,1], diff = 1
Output: 3
Explanation:
There are 3 pairs that satisfy the conditions:
1. i = 0, j = 1: 3 - 2 <= 2 - 2 + 1. Since i < j and 1 <= 1, this pair satisfies the conditions.
2. i = 0, j = 2: 3 - 5 <= 2 - 1 + 1. Since i < j and -2 <= 2, this pair satisfies the conditions.
3. i = 1, j = 2: 2 - 5 <= 2 - 1 + 1. Since i < j and -3 <= 2, this pair satisfies the conditions.
Therefore, we return 3.
Python Solution
class BinaryIndexedTree:
def __init__(self, n):
self.n = n
self.c = [0] * (n + 1)
def lowbit(x):
return x & -x
def update(self, x, delta):
while x <= self.n:
self.c[x] += delta
x += BinaryIndexedTree.lowbit(x)
def query(self, x):
s = 0
while x:
s += self.c[x]
x -= BinaryIndexedTree.lowbit(x)
return s
class Solution:
def numberOfPairs(self, nums1: List[int], nums2: List[int], diff: int) -> int:
tree = BinaryIndexedTree(10**5)
ans = 0
for a, b in zip(nums1, nums2):
v = a - b
ans += tree.query(v + diff + 40000)
tree.update(v + 40000, 1)
return ans
Complexity
The time complexity is . The space complexity is O(1).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.