⚡Flashcard Drill➔
NeetCode #293LC-2563MediumBinary Search
← Back to All Problems

#293 · #2563 · Count the Number of Fair Pairs(统计公平数对的数目)

📌 Problem Statement & Constraints

Given a 0-indexed integer array nums and two integers lower and upper, return the number of fair pairs: pairs (i, j) with i < j and lower <= nums[i] + nums[j] <= upper. Constraints: 1 <= nums.length <= 10^5, -10^9 <= nums[i], lower, upper <= 10^9.

💡 Core Algorithmic Approaches

  1. Counting pairs within a range is the difference of two counts: pairs with sum at most upper minus pairs with sum at most lower - 1.
  2. For a fixed limit, sort the array and use two pointers: if nums[l] + nums[r] <= limit, then all r - l pairs with this l and any j in (l, r] are valid.
  3. Advance l on success and decrement r otherwise.
  4. This is O(n log n) overall, dominated by the sort.

💻 Benchmark Python3 Implementation

class Solution:
    def countFairPairs(self, nums: List[int], lower: int, upper: int) -> int:
        nums.sort()

        def count_at_most(limit: int) -> int:
            l, r = 0, len(nums) - 1
            res = 0
            while l < r:
                if nums[l] + nums[r] <= limit:
                    res += r - l           # all pairs (l, l+1..r) qualify
                    l += 1
                else:
                    r -= 1
            return res

        # inclusive range = at most upper minus at most (lower - 1)
        return count_at_most(upper) - count_at_most(lower - 1)

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n log n): the sort plus two linear scans.
💾 Space Complexity
O(1) beyond the sort.

⚠️ Interview Pitfalls & Follow-ups

  • Using two pointers directly for the range: the range has two bounds, so the subtraction of two one-sided counts is the clean way.
  • Using count_at_most(lower): that excludes pairs summing exactly to lower; the subtraction uses lower - 1.
  • Sorting inside count_at_most: the sort happens once, outside.
  • Assuming values are positive: they can be negative, and the two-pointer logic is unaffected.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Binary Search Problems

中文速览与面试要点

统计公平数对的数目

给你一个下标从 0 开始、长度为 n 的整数数组 nums,和两个整数 lower 和 upper,返回 公平数对 的数目。如果 (i, j) 满足以下条件,则被称为 公平数对 : 0 &lt;= i &lt; j &lt; n ,且 lower &lt;= nums[i] + nums[j] &lt;= upper 。约束:1 ≤ nums.length ≤ 10^5;nums.length == n;-10^9 ≤ nums[i] ≤ 10^9;-10^9 ≤ lower &lt;= upper ≤ 10^9。

核心要点

  • 排序 + 双指针「至多」作差(标准解) :排序后,`和为 [lower, upper] 的对数 = 「和 ≤ upper 的对数」−「和 ≤ lower−1 的对数」。
  • 计数 ≤ limit 的对数 :用相向双指针。若 nums[l] + nums[r] &lt;= limit ,则 nums[l] 与 nums[l+1..r] 中任意一个配对都满足,一次累加 r − l 个,然后 l += 1 ;否则 r -= 1 。
  • 为什么可以一次累加 r − l :数组已升序,固定 l 时 nums[r] 是可选的最大值;既然它与 nums[l] 的和都 ≤ limit,那么更小的 nums[j] (l &lt; j &lt; r)必然也满足。
  • 下标对的唯一性 :由于只累加 j &gt; l 的组合,每对只被计一次。

常见陷阱

  • 用双重循环枚举所有数对 :O(n²) 在 n = 10^5 时必然超时。
  • 满足条件时只 res += 1 :会严重少计。必须一次累加 r − l 。
  • 忘记减 1 :区间是 [lower, upper] ,因此第二个计数应为 count_at_most(lower − 1) 。
  • 满足条件时让 r 左移 :方向反了。 nums[l] + nums[r] 已满足,应增大 l 以探索新的组合。
  • 用哈希表统计(类似 1 两数之和) :需要枚举所有可能的和值,区间范围太大不可行。

参考实现

class Solution:
    def countFairPairs(self, nums: list[int], lower: int, upper: int) -> int:
        nums.sort()

        def count_at_most(limit: int) -> int:
            """数对 (i < j) 满足 nums[i] + nums[j] <= limit 的个数。"""
            l, r = 0, len(nums) - 1
            res = 0
            while l < r:
                if nums[l] + nums[r] <= limit:
                    res += r - l        # nums[l] 与 l+1..r 中任一个都满足
                    l += 1
                else:
                    r -= 1
            return res

        # [lower, upper] 的个数 = <= upper 的个数 - <= lower-1 的个数
        return count_at_most(upper) - count_at_most(lower - 1)