Count the Number of Fair Pairs (LeetCode 2563): Solution and Explanation

Medium
Array
Two Pointers
Binary Search
Sorting

Count the pairs i < j whose sum lies in [lower, upper]. The count can pass 2^31, so it is returned as a 64-bit integer.

Intuition

A pair is defined by two values, and the condition only looks at their sum. Reordering the array maps pairs to pairs one to one, so sorting does not change the answer, and sorted order is what makes counting fast.

A range condition is awkward, but a single bound is easy. Pairs with lower <= sum <= upper are the pairs with sum <= upper minus the pairs with sum < lower, so count below a limit twice and subtract.

To count pairs with sum below a limit on a sorted array, put left at the start and right at the end. If nums[left] + nums[right] fits, then nums[left] also fits with every value between them, because those are no larger than nums[right]. That is right - left pairs in one step. If it does not fit, nums[right] is too big even for the smallest remaining partner, so it can be dropped.

Approach: Sort and two pointers, twice

  1. Sort nums.
  2. Define countBelow(limit): start with left = 0, right = n - 1, total = 0.
  3. While left < right: if nums[left] + nums[right] < limit, add right - left to total and move left up; otherwise move right down.
  4. Return countBelow(upper + 1) - countBelow(lower).
  5. Use 64-bit integers for the sums and the totals.

Step-by-step example

nums = [0,1,7,4,4,5], lower = 3, upper = 6
  1. Sorted: [0,1,4,4,5,7].
  2. countBelow(7): 0+7 too big, drop 7. 0+5 < 7 adds 4. 1+5 < 7 adds 3. 4+5 too big, drop 5. 4+4 < 7? No, drop. Total 7.
  3. countBelow(3): 0+7, 0+5, 0+4, 0+4 too big, drop each. 0+1 < 3 adds 1. Total 1.
  4. Answer 7 - 1 = 6.

Code: Python, Java, C++

1class Solution:
2    def countFairPairs(self, nums: List[int], lower: int, upper: int) -> int:
3        nums.sort()
4        def count_below(limit: int) -> int:
5            total = 0
6            left, right = 0, len(nums) - 1
7            while left < right:
8                if nums[left] + nums[right] < limit:
9                    total += right - left
10                    left += 1
11                else:
12                    right -= 1
13            return total
14        return count_below(upper + 1) - count_below(lower)
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n log n)

Sorting costs O(n log n). Each counting pass moves one pointer per step, so it is O(n).

Space

O(1)

Apart from the space the sort uses, only pointers and totals are kept.

Other approaches

Sort and binary search (time O(n log n), space O(1))

After sorting, for each i find with two binary searches the range of j > i where lower - nums[i] <= nums[j] <= upper - nums[i], and add its length.

Brute force (time O(n^2), space O(1))

Check every pair i < j. Correct but far too slow for n up to 10^5.

Common mistakes

  • Storing the answer in a 32-bit int. With n = 10^5 there are almost 5 * 10^9 pairs, which overflows.
  • Adding two values in 32 bits. nums[i] can be 10^9, so the sum of two can reach 2 * 10^9 and overflow in Java, C++ or C#.
  • Counting only below upper and forgetting to subtract the pairs below lower, or using <= lower and dropping pairs whose sum equals lower.

Frequently asked questions

Why is sorting allowed when the problem says i < j?

i < j only stops a pair from being counted twice. The set of unordered pairs of positions is the same after sorting, and each one keeps its sum, so the count does not change.

Why add right - left at once?

The array is sorted, so every index between left and right holds a value no larger than nums[right]. If nums[left] + nums[right] is below the limit, nums[left] plus any of them is too.

Is this really binary search?

The binary-search version does the same counting with bisect calls per element. The two-pointer pass replaces those searches with pointer moves that only go one way, which is the same monotone idea.