Count the Number of Fair Pairs (LeetCode 2563): Solution and Explanation
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
- Sort
nums. - Define
countBelow(limit): start withleft = 0,right = n - 1,total = 0. - While
left < right: ifnums[left] + nums[right] < limit, addright - lefttototaland moveleftup; otherwise moverightdown. - Return
countBelow(upper + 1) - countBelow(lower). - 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
- Sorted: [0,1,4,4,5,7].
- 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.
- countBelow(3): 0+7, 0+5, 0+4, 0+4 too big, drop each. 0+1 < 3 adds 1. Total 1.
- 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)1class Solution {
2 public long countFairPairs(int[] nums, int lower, int upper) {
3 Arrays.sort(nums);
4 return countBelow(nums, (long) upper + 1) - countBelow(nums, lower);
5 }
6 private long countBelow(int[] nums, long limit) {
7 long total = 0;
8 int left = 0, right = nums.length - 1;
9 while (left < right) {
10 if ((long) nums[left] + nums[right] < limit) {
11 total += right - left;
12 left++;
13 } else {
14 right--;
15 }
16 }
17 return total;
18 }
19}1class Solution {
2public:
3 long long countFairPairs(vector<int>& nums, int lower, int upper) {
4 sort(nums.begin(), nums.end());
5 return countBelow(nums, (long long) upper + 1) - countBelow(nums, lower);
6 }
7private:
8 long long countBelow(vector<int>& nums, long long limit) {
9 long long total = 0;
10 int left = 0, right = (int) nums.size() - 1;
11 while (left < right) {
12 if ((long long) nums[left] + nums[right] < limit) {
13 total += right - left;
14 left++;
15 } else {
16 right--;
17 }
18 }
19 return total;
20 }
21};Time and space complexity
O(n log n)
Sorting costs O(n log n). Each counting pass moves one pointer per step, so it is O(n).
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.