LeetCode solutions

2699. Count the Number of Fair Pairs

My accepted Python solution to LeetCode problem 2699, Count the Number of Fair Pairs, running in 284ms.

  • Difficulty: Medium
  • Python
  • Runtime 284ms
  • Memory 30.6MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 284ms, memory 30.6MB, accepted 2025-12-29.

python
class Solution:
    def countFairPairs(self, nums: List[int], lower: int, upper: int) -> int:
        # Sort and use binary search
        # Time: O(n log n), Space: O(n) for sorting
        from bisect import bisect_left, bisect_right
        
        nums.sort()
        n = len(nums)
        count = 0
        
        for i in range(n):
            # Find j > i such that lower <= nums[i] + nums[j] <= upper
            # lower - nums[i] <= nums[j] <= upper - nums[i]
            lo = lower - nums[i]
            hi = upper - nums[i]
            
            # Search in nums[i+1:]
            left_idx = bisect_left(nums, lo, i + 1)
            right_idx = bisect_right(nums, hi, i + 1)
            
            count += right_idx - left_idx
        
        return count

Source