#2426

Number of Pairs Satisfying Inequality

Hard
ArrayBinary SearchDivide and ConquerBinary Indexed TreeSegment TreeMerge SortOrdered SetBinary SearchSortingTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

By rearranging the inequality and using a data structure like a Fenwick Tree (Binary Indexed Tree), we can efficiently count valid pairs without checking every combination, reducing the time complexity significantly.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a new array 'transformed' where each element is calculated as nums1[i] - nums2[i] + diff.
  2. 2Step 2: Sort the 'transformed' array to facilitate efficient counting.
  3. 3Step 3: For each element in the original array, use binary search to find how many elements in 'transformed' are less than or equal to the current element.
  4. 4Step 4: Sum these counts to get the total number of valid pairs.
solution.py8 lines
1def countPairs(nums1, nums2, diff):
2    n = len(nums1)
3    transformed = [nums1[i] - nums2[i] + diff for i in range(n)]
4    transformed.sort()
5    count = 0
6    for i in range(n):
7        count += bisect.bisect_right(transformed, nums1[i]) - (i + 1)
8    return count

Complexity note: The time complexity is O(n log n) due to sorting the transformed array, and the space complexity is O(n) for storing the transformed values.

  • 1Rearranging the inequality can simplify the problem significantly.
  • 2Using efficient data structures can reduce the time complexity from quadratic to logarithmic.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.