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, and
  • lower <= 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
Count Fair Pairs: nums=[0,1,7,4,4,5], lower=3, upper=6017445i=0i=1i=2i=3i=4i=5Valid Range: 3 ≤ pair sum ≤ 6✓ Valid Pairs:(0,3): 0+4=4 ✓(0,4): 0+4=4 ✓(0,5): 0+5=5 ✓(1,3): 1+4=5 ✓(1,4): 1+4=5 ✓(1,5): 1+5=6 ✓✗ Invalid Pairs:(0,1): 0+1=1 < 3(0,2): 0+7=7 > 6(1,2): 1+7=8 > 6Count Result6 Fair PairsAll with sum ∈ [3,6]
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)
Asked in
Google 25 Amazon 18 Microsoft 15 Meta 12
28.5K Views
Medium Frequency
~25 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen