#2563
Count the Number of Fair Pairs
MediumArrayTwo PointersBinary SearchSortingTwo PointersBinary SearchSorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log n)Space O(1)
By sorting the array and using a two-pointer technique, we can efficiently find the number of fair pairs without checking every possible combination. This reduces the time complexity significantly.
⚙️
Algorithm
5 steps- 1Step 1: Sort the array nums.
- 2Step 2: Initialize a counter for fair pairs.
- 3Step 3: For each element nums[i], use binary search to find the range of indices that can form fair pairs with nums[i].
- 4Step 4: Count the valid pairs using the indices found in the previous step and update the counter.
- 5Step 5: Return the counter as the result.
solution.py15 lines
1# Full working Python code
2import bisect
3
4def countFairPairs(nums, lower, upper):
5 nums.sort()
6 count = 0
7 n = len(nums)
8 for i in range(n):
9 left = bisect.bisect_left(nums, lower - nums[i], i + 1)
10 right = bisect.bisect_right(nums, upper - nums[i], i + 1)
11 count += right - left
12 return count
13
14# Example usage
15print(countFairPairs([0,1,7,4,4,5], 3, 6)) # Output: 6ℹ
Complexity note: The sorting step takes O(n log n), and the two-pointer technique runs in O(n), making this approach much more efficient than the brute force method.
- 1Sorting the array allows us to efficiently find pairs that meet the criteria using binary search.
- 2Using two pointers or binary search reduces the number of comparisons significantly.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.