Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created April 19, 2025 19:28
Show Gist options
  • Save Ifihan/b8eec739be3538d019971f215e152fff to your computer and use it in GitHub Desktop.
Save Ifihan/b8eec739be3538d019971f215e152fff to your computer and use it in GitHub Desktop.
Count the Number of Fair Pairs

Question

Approach

Implementation

from bisect import bisect_left, bisect_right

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

        for i in range(n):
            left = bisect_left(nums, lower - nums[i], i + 1, n)
            right = bisect_right(nums, upper - nums[i], i + 1, n)
            count += right - left

        return count

Complexities

  • Time: O(n logn)
  • Space: O(1)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment