Number of Pairs Satisfying Inequality — LeetCode 2426 Python Solution

HardBinary Indexed TreeSegment TreeArrayBinary SearchDivide and ConquerOrdered SetMerge Sort
Problem
#2426
Reading time
6 min

The problem

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.

Example

Input
nums1 = [3,2,5], nums2 = [2,2,1], diff = 1
Output
3
Explanation
There are 3 pairs that satisfy the conditions:

Python solution

Python
class BinaryIndexedTree:
    def __init__(self, n):
        self.n = n
        self.c = [0] * (n + 1)

    @staticmethod
    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

MeasureComplexity
TimeO(n \times \log n)
SpaceO(1) auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 2426. Number of Pairs Satisfying Inequality is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2426. Number of Pairs Satisfying Inequality?
LeetCode 2426. Number of Pairs Satisfying Inequality is rated Hard on LeetCode.
What is the time complexity of LeetCode 2426. Number of Pairs Satisfying Inequality?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 2426. Number of Pairs Satisfying Inequality?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2426. Number of Pairs Satisfying Inequality cover?
LeetCode 2426. Number of Pairs Satisfying Inequality is tagged Binary Indexed Tree, Segment Tree, Array, Binary Search, Divide and Conquer, Ordered Set and Merge Sort on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview