Count the Number of Fair Pairs — LeetCode 2563 Python Solution

MediumArrayTwo PointersBinary SearchSorting
Problem
#2563
Reading time
2 min

The problem

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

This statement is abridged. Read the full problem on LeetCode.

Example

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).

Python solution

Python
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

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(\log n) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 2563. Count the Number of Fair Pairs is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2563. Count the Number of Fair Pairs?
LeetCode 2563. Count the Number of Fair Pairs is rated Medium on LeetCode.
What is the time complexity of LeetCode 2563. Count the Number of Fair Pairs?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 2563. Count the Number of Fair Pairs?
The Python solution on this page uses O(\log n) auxiliary space.
What topics does LeetCode 2563. Count the Number of Fair Pairs cover?
LeetCode 2563. Count the Number of Fair Pairs is tagged Array, Two Pointers, Binary Search and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview