Count the Number of Fair Pairs - Problem
Given a 0-indexed integer array nums of size n and two integers lower and upper, return the number of fair pairs.
A pair (i, j) is fair if:
0 <= i < j < n, andlower <= nums[i] + nums[j] <= upper
Input & Output
Example 1 — Basic Case
$
Input:
nums = [0,1,7,4,4,5], lower = 3, upper = 6
›
Output:
6
💡 Note:
Valid pairs: (0,3)→4, (0,4)→4, (0,5)→5, (1,3)→5, (1,4)→5, (1,5)→6. All sums are between 3 and 6 inclusive.
Example 2 — No Valid Pairs
$
Input:
nums = [1,7,9,2,5], lower = 11, upper = 11
›
Output:
1
💡 Note:
Only one pair sums to 11: (2,3) where nums[2]=9 and nums[3]=2, giving 9+2=11.
Example 3 — All Pairs Valid
$
Input:
nums = [1,2,3], lower = 3, upper = 5
›
Output:
3
💡 Note:
All pairs are valid: (0,1)→3, (0,2)→4, (1,2)→5. Each sum is in range [3,5].
Constraints
- 1 ≤ nums.length ≤ 105
- -109 ≤ nums[i], lower, upper ≤ 109
- lower ≤ upper
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array with lower and upper bounds for pair sums
2
Process
Find all pairs whose sum falls in the given range
3
Output
Count of valid pairs
Key Takeaway
🎯 Key Insight: Sorting the array enables efficient range queries using binary search or two pointers, reducing time from O(n²) to O(n log n)
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code