Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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] <= upperExample 1:
Input: nums = [0,1,7,4,4,5], lower = 3, upper = 6 Output: 6 Explanation: There are 6 fair pairs: (0,3), (0,4), (0,5), (1,3), (1,4), and (1,5).
Example 2:
Input: nums = [1,7,9,2,5], lower = 11, upper = 11 Output: 1 Explanation: There is a single fair pair: (2,3).
Constraints:
1 <= nums.length <= 105nums.length == n-109 <= nums[i] <= 109-109 <= lower <= upper <= 109Problem summary: 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
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Two Pointers · Binary Search
[0,1,7,4,4,5] 3 6
[1,7,9,2,5] 11 11
count-of-range-sum)finding-pairs-with-a-certain-sum)count-number-of-pairs-with-absolute-difference-k)count-pairs-whose-sum-is-less-than-target)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2563: Count the Number of Fair Pairs
class Solution {
public long countFairPairs(int[] nums, int lower, int upper) {
Arrays.sort(nums);
long ans = 0;
int n = nums.length;
for (int i = 0; i < n; ++i) {
int j = search(nums, lower - nums[i], i + 1);
int k = search(nums, upper - nums[i] + 1, i + 1);
ans += k - j;
}
return ans;
}
private int search(int[] nums, int x, int left) {
int right = nums.length;
while (left < right) {
int mid = (left + right) >> 1;
if (nums[mid] >= x) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
}
// Accepted solution for LeetCode #2563: Count the Number of Fair Pairs
func countFairPairs(nums []int, lower int, upper int) (ans int64) {
sort.Ints(nums)
for i, x := range nums {
j := sort.Search(len(nums), func(h int) bool { return h > i && nums[h] >= lower-x })
k := sort.Search(len(nums), func(h int) bool { return h > i && nums[h] >= upper-x+1 })
ans += int64(k - j)
}
return
}
# Accepted solution for LeetCode #2563: Count the Number of Fair Pairs
class Solution:
def countFairPairs(self, nums: List[int], lower: int, upper: int) -> int:
nums.sort()
ans = 0
for i, x in enumerate(nums):
j = bisect_left(nums, lower - x, lo=i + 1)
k = bisect_left(nums, upper - x + 1, lo=i + 1)
ans += k - j
return ans
// Accepted solution for LeetCode #2563: Count the Number of Fair Pairs
struct Solution;
fn lower_bound(nums: &[i32], bound: i32) -> i64 {
let mut l = 0;
let mut r = nums.len() - 1;
let mut res = 0;
while l < r {
let sum = nums[l] + nums[r];
if sum < bound {
res += r - l;
l += 1;
} else {
r -= 1;
}
}
res as i64
}
impl Solution {
pub fn count_fair_pairs(mut nums: Vec<i32>, lower: i32, upper: i32) -> i64 {
nums.sort();
lower_bound(&nums, upper + 1) - lower_bound(&nums, lower)
}
}
#[test]
fn test() {
let nums = vec![0, 1, 7, 4, 4, 5];
let lower = 3;
let upper = 6;
let res = 6;
assert_eq!(Solution::count_fair_pairs(nums, lower, upper), res);
let nums = vec![1, 7, 9, 2, 5];
let lower = 11;
let upper = 11;
let res = 1;
assert_eq!(Solution::count_fair_pairs(nums, lower, upper), res);
let nums = vec![0, 0, 0, 0, 0, 0];
let lower = 0;
let upper = 0;
let res = 15;
assert_eq!(Solution::count_fair_pairs(nums, lower, upper), res);
}
// Accepted solution for LeetCode #2563: Count the Number of Fair Pairs
function countFairPairs(nums: number[], lower: number, upper: number): number {
const search = (x: number, l: number): number => {
let r = nums.length;
while (l < r) {
const mid = (l + r) >> 1;
if (nums[mid] >= x) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
};
nums.sort((a, b) => a - b);
let ans = 0;
for (let i = 0; i < nums.length; ++i) {
const j = search(lower - nums[i], i + 1);
const k = search(upper - nums[i] + 1, i + 1);
ans += k - j;
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair of elements. The outer loop picks one element, the inner loop scans the rest. For n elements that is n × (n−1)/2 comparisons = O(n²). No extra memory — just two loop variables.
Each pointer traverses the array at most once. With two pointers moving inward (or both moving right), the total number of steps is bounded by n. Each comparison is O(1), giving O(n) overall. No auxiliary data structures are needed — just two index variables.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Advancing both pointers shrinks the search space too aggressively and skips candidates.
Usually fails on: A valid pair can be skipped when only one side should move.
Fix: Move exactly one pointer per decision branch based on invariant.
Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.
Usually fails on: Two-element ranges never converge.
Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.