Count the Number of Fair Pairs

Medium Topics Company Tags

Given an integer array nums and inclusive bounds lower and upper, count the pairs of different indices i < j for which lower <= nums[i] + nums[j] <= upper. Each pair of indices counts separately, even if some array values are equal. Return the total number of qualifying pairs.

Example 1:

Input: nums = [2,2,2]
lower = 4
upper = 4

Output: 3

Explanation: Any two entries sum to 4. The three index pairs (0,1), (0,2), and (1,2) all qualify, even though the values are identical.

Example 2:

Input: nums = [-3,1,2,5]
lower = -1
upper = 3

Output: 3

Explanation: The qualifying pairs have values (-3,2), (-3,5), and (1,2), with sums -1, 2, and 3. The bounds are inclusive, so all three count.

Example 3:

Input: nums = [4]
lower = 0
upper = 8

Output: 0

Explanation: There is only one index. A pair requires two different indices, so the count is 0.

Constraints:

  • 1 <= nums.length <= 100000
  • -1000000000 <= nums[i] <= 1000000000
  • -1000000000 <= lower <= upper <= 1000000000


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.