LeetCode 2563. Count the Number of Fair Pairs Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
2563. Count the Number of Fair Pairs

Description

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

 

Example 1:

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

Example 2:

Input: nums = [1,7,9,2,5], lower = 11, upper = 11
Output: 1
Explanation: There is a single fair pair: (2,3).

 

Constraints:

  • 1 <= nums.length <= 105
  • nums.length == n
  • -109 <= nums[i] <= 109
  • -109 <= lower <= upper <= 109

Solutions

Solution 1: Sorting + Binary Search

First, we sort the array nums in ascending order. Then, for each nums[i], we use binary search to find the lower bound j of nums[j], i.e., the first index that satisfies nums[j] >= lower - nums[i]. Then, we use binary search again to find the lower bound k of nums[k], i.e., the first index that satisfies nums[k] >= upper - nums[i] + 1. Therefore, [j, k) is the index range for nums[j] that satisfies lower <= nums[i] + nums[j] <= upper. The count of these indices corresponding to nums[j] is k - j, and we can add this to the answer. Note that j > i.

The time complexity is O(n × log n), and the space complexity is O(log n). Where n is the length of the array nums.

PythonJavaC++GoTypeScript
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(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !