The Count the Number of Fair Pairs coding problem provides an array of integers and two thresholds: lower and upper. A pair of indices is considered "fair" if and the sum of the elements at these indices falls within the range .
Your task is to return the total count of such unique pairs.
This is a high-signal problem for companies like Microsoft, Qualcomm, and Meta. It tests a candidate's ability to optimize a search from to . It evaluates proficiency with the sorting interview pattern and the two pointers interview pattern (specifically the "sliding window" version for sums). It’s also an excellent test of whether you can decompose a "range count" problem into two "upper bound count" problems.
This problem is solved using Sorting and Two Pointers.
countPairsWithSum(upper) - countPairsWithSum(lower - 1).sum <= target, initialize left = 0 and right = n - 1. If nums[left] + nums[right] <= target, then all pairs between left and right (e.g., (left, left+1), ..., (left, right)) are valid. Increment count by right - left and move left. Otherwise, move right.nums = [3, 1, 4, 2], lower = 4, upper = 5
nums: [1, 2, 3, 4].L=0(1), R=3(4): . Count += 3. L=1.L=1(2), R=3(4): . R=2.L=1(2), R=2(3): . Count += 1. L=2.L=0(1), R=3(4): . R=2.L=0(1), R=2(3): . R=1.L=0(1), R=1(2): . Count += 1. L=1.countPairsWithSum(lower) instead of countPairsWithSum(lower - 1).Whenever you need to count items in a range , always ask yourself if calculating f(B) - f(A-1) is easier. This "prefix property" applies to array sums, frequency counts, and pair sums alike.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Number of Subsequences That Satisfy the Given Sum Condition | Medium | Solve | |
| Successful Pairs of Spells and Potions | Medium | Solve | |
| Friends Of Appropriate Ages | Medium | Solve | |
| The Latest Time to Catch a Bus | Medium | Solve | |
| Heaters | Medium | Solve |