This problem tests our understanding of efficient array traversal techniques and highlights the power of binary search when working with sorted arrays. By the end of this post, you’ll have a clear, optimized solution in C++ that avoids Time Limit Exceeded (TLE) errors and uses two-pointer and binary search techniques.
Let’s get started by breaking down the problem and exploring a step-by-step approach to a performant solution.
Problem Statement
Given:
- An integer array
numsof sizen. - Two integers,
lowerandupper.
Our goal is to count all pairs (i, j) where:
0 <= i < j < n, andlower <= nums[i] + nums[j] <= upper.
Example Walkthrough
Let's clarify with an example:
Example 1
- Input:
nums = [0, 1, 7, 4, 4, 5],lower = 3,upper = 6 - Output:
6 - Explanation: Valid pairs that satisfy the condition are
(0,3),(0,4),(0,5),(1,3),(1,4), and(1,5).
Example 2
- Input:
nums = [1, 7, 9, 2, 5],lower = 11,upper = 11 - Output:
1 - Explanation: There is only one valid pair:
(2, 3).
Constraints
1 <= nums.length <= 10^5-10^9 <= nums[i], lower, upper <= 10^9
With the constraints, a brute-force approach will fail due to excessive runtime. This is where sorting and binary search come into play.
Strategy: Optimized Approach with Sorting and Binary Search
To solve this problem efficiently, we’ll use the following approach:
- Sort the Array: Sorting enables us to efficiently search for valid pairs using binary search, which will significantly reduce the number of operations.
- Binary Search for Range: For each element
nums[i], we’ll determine a valid range ofnums[j]values that can form a fair pair withnums[i]. We’ll find the start and end of this range using:lower_boundto get the minimum validnums[j].upper_boundto get the maximum validnums[j].
- Calculate Pair Count: For each
i, the differenceright - left(from binary search results) gives us the count of validjvalues. Summing these differences gives the total number of fair pairs.
Step-by-Step Solution Code
Here’s the complete C++ code for this approach:
Explanation of Key Steps
Sorting (
O(n log n)):- Sorting allows us to leverage binary search, which is much faster than checking each potential pair individually.
Binary Search for Valid
jValues (O(log n)):- For each
i, we calculate alowandupthreshold based on the values oflowerandupper. - Using
lower_boundandupper_boundon the range starting fromi + 1, we get the count ofjvalues wherenums[i] + nums[j]lies within[lower, upper].
- For each
Efficient Pair Count Calculation:
right - lefttells us exactly how many valid pairs exist withnums[i]as the first element.
Complexity Analysis
- Time Complexity:
- Space Complexity:
This solution is optimized for large inputs, avoiding TLE even when n reaches 10^5.
Why This Solution Works
The combination of sorting and binary search allows us to take advantage of the sorted order of nums. By transforming the problem into finding ranges of j values, we sidestep the need for nested loops and keep operations efficient. This is a great example of how sorting and binary search can simplify complex pairing problems.
FAQs for LeetCode 2563: Count the Number of Fair Pairs
A fair pair is a pair of indices (i, j) where:
- 0
<= i < j < n (indices are ordered).
- The
sum nums[i] + nums[j] lies between lower and upper (inclusive).
A brute-force solution (checking all possible pairs) has O(n²) time complexity, which is too slow for constraints like n = 10^5. Sorting + binary search reduces it to O(n log n).
Sorting enables binary search, allowing us to find valid j values for each i in O(log n) time instead of O(n).
4. How does lower_bound and upper_bound work
here?
- lower_bound(nums.begin(),
nums.end(), low) finds the first j where nums[j] >=
lower - nums[i].
- upper_bound(nums.begin(),
nums.end(), up) finds the first j where nums[j] >
upper - nums[i].
The difference (right - left) gives the count of valid j values for nums[i].
5. What’s the time complexity of the optimized solution?
- O(n
log n) for sorting.
- O(n
log n) for binary searches (n elements × O(log n) per search).
Total: O(n log n).
To avoid counting duplicates or pairs where j <= i (since i < j is required).
Yes! After sorting, use two pointers (left/right) to find valid ranges for each i. However, binary search is more intuitive for this problem.
The solution still works because sorting handles negatives correctly (e.g., -5 + 10 = 5 is treated the same as 3 + 2).
9. How does the code avoid integer overflow?
- The
constraints allow nums[i] up to ±1e9, but lower - nums[i] and upper
- nums[i] are computed as integers.
- Using long
long for count prevents overflow when summing large counts.
No, because hash maps don’t help in finding ranges of values (binary search requires sorted order).
O(1) extra space (ignoring sorting, which may use O(log n) stack space in quicksort).
For nums = [0,1,7,4,4,5], valid pairs are:
(0,3)=4, (0,4)=4, (0,5)=5, (1,3)=5, (1,4)=5, (1,5)=6 → Total 6.
The solution already handles duplicates because sorting groups them, and binary search counts all valid js (including duplicates).
Partially, but Two Sum finds exact sums, whereas this problem counts sums in a range.
It finds the first element greater than upper - nums[i], so right - left counts values ≤ upper.
Sliding windows work for contiguous subarrays, but this problem needs any pairs, so binary search is better.
The answer is 0 (no valid pairs exist since the range is invalid).
Change the binary search to start from i instead of i + 1 and adjust bounds to avoid double-counting.
For large n (e.g., 1e5), the count can exceed INT_MAX.
Yes! For triplets, sort and fix two indices, then binary search for the third. Time complexity becomes O(n² log n).
LeetCode 2563: Count the Number of Fair Pairs can be solved efficiently using sorting and binary search. By following this method, we achieve optimal performance without sacrificing readability. Remember, whenever you face a pairing problem, consider sorting and using binary search to find ranges—it might be the key to an efficient solution!
With this approach, you’re ready to tackle similar problems on LeetCode and beyond. If you found this helpful, feel free to share or bookmark it for your coding journey!
