Count the Number of Fair Pairs - Problem
๐ฏ Count the Number of Fair Pairs
Imagine you're organizing a team-building activity where participants need to be paired up based on their combined skill levels. You have an array of skill ratings and need to find pairs that fall within an acceptable range!
Given a 0-indexed integer array nums of size n and two integers lower and upper, your task is to count how many "fair pairs" exist in the array.
A pair (i, j) is considered fair if:
0 <= i < j < n(different indices, order matters)lower <= nums[i] + nums[j] <= upper(sum within acceptable range)
Example: If nums = [0,1,7,4,4,5], lower = 3, upper = 6
Valid pairs: (1,3), (1,4), (1,5), (2,3), (3,4), (4,5)
Answer: 6 fair pairs
Input & Output
example_1.py โ Basic Case
$
Input:
nums = [0,1,7,4,4,5], lower = 3, upper = 6
โบ
Output:
6
๐ก Note:
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 โ. Total: 6 pairs
example_2.py โ Edge Case
$
Input:
nums = [1,7,9,2,5], lower = 11, upper = 11
โบ
Output:
1
๐ก Note:
Only one pair sums to exactly 11: (2,4) where nums[2]=9 and nums[4]=5, so 9+5=11. All other pairs sum to different values.
example_3.py โ No Valid Pairs
$
Input:
nums = [1,2,3], lower = 10, upper = 15
โบ
Output:
0
๐ก Note:
Maximum possible sum is 2+3=5, which is less than lower=10. No pairs can satisfy the condition lower โค sum โค upper.
Constraints
- 1 โค nums.length โค 105
- -109 โค nums[i], lower, upper โค 109
- lower โค upper (guaranteed valid range)
Visualization
Tap to expand
Understanding the Visualization
1
Sort for Efficiency
Line up all elements in order to enable binary search - like organizing a speed dating event by age
2
Calculate Valid Range
For each element, determine what values its partner needs to have for their sum to be 'fair'
3
Binary Search Bounds
Quickly find the leftmost and rightmost valid partners using binary search
4
Count the Range
Count all valid partners in one operation instead of checking each individually
Key Takeaway
๐ฏ Key Insight: Sorting enables us to use binary search for range counting, transforming an O(nยฒ) pair-checking problem into an O(n log n) range-finding solution!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code