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 the Number of Fair Pairs INPUT nums array (n=6) 0 i=0 1 i=1 7 i=2 4 i=3 4 i=4 5 i=5 Constraints lower = 3 upper = 6 Fair Pair Condition: 0 <= i < j < n 3 <= nums[i]+nums[j] <= 6 Input Values nums = [0,1,7,4,4,5] lower=3, upper=6 ALGORITHM STEPS 1 Sort the Array [0,1,4,4,5,7] 2 For each i, use binary search on j>i 3 Find valid j range lower-nums[i] to upper-nums[i] 4 Count pairs in range Sum all valid pairs Fair Pairs Found: (0,3): 0+4=4 [OK] (0,4): 0+4=4 [OK] (0,5): 0+5=5 [OK] (1,3): 1+4=5 [OK] (1,4): 1+4=5 [OK] (1,5): 1+5=6 [OK] Time: O(n log n) FINAL RESULT Fair Pairs Count 6 All 6 Valid Pairs: (0,4)=4 (0,4)=4 (0,5)=5 (1,4)=5 (1,4)=5 (1,5)=6 Output 6 Key Insight: Sorting enables binary search to find valid j values for each i. Instead of checking all O(n^2) pairs, we use lower_bound and upper_bound to find the range where lower-nums[i] <= nums[j] <= upper-nums[i]. This reduces time complexity from O(n^2) to O(n log n). Count = pairs with sum <= upper - pairs with sum < lower. TutorialsPoint - Count the Number of Fair Pairs | Optimal Solution (Binary Search)
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