Leetcode 2563: Count the Number of Fair Pairs

grid47
grid47
Exploring patterns and algorithms
Feb 24, 2024 6 min read

Given an integer array nums of size n and two integers lower and upper, find the number of fair pairs. A pair (i, j) is considered fair if it satisfies the following conditions:

  • 0 <= i < j < n
  • lower <= nums[i] + nums[j] <= upper

Return the number of such pairs.

Problem
Approach
Steps
Complexity
Input: You are given an array of integers `nums` of size `n`, and two integers `lower` and `upper`.
Example: nums = [0,1,7,4,4,5], lower = 3, upper = 6
Constraints:
• 1 <= nums.length <= 10^5
• -10^9 <= nums[i] <= 10^9
• -10^9 <= lower <= upper <= 10^9
Output: Return the number of fair pairs (i, j) satisfying the given conditions.
Example: Output: 6
Constraints:
• The output should be a single integer representing the number of fair pairs.
Goal: To count the number of fair pairs (i, j) such that the sum of `nums[i] + nums[j]` lies within the range [lower, upper].
Steps:
• Sort the array `nums` to efficiently check pairs.
• For each element in the array, calculate the range [lower - nums[i], upper - nums[i]] for the second element of the pair.
• Use binary search to find the bounds for valid second elements in the array.
• Count the number of pairs (i, j) that satisfy the condition `lower <= nums[i] + nums[j] <= upper`.
Goal: The constraints on the input values ensure the array size and integer values are within manageable ranges.
Steps:
• 1 <= nums.length <= 10^5
• -10^9 <= nums[i] <= 10^9
• -10^9 <= lower <= upper <= 10^9
Assumptions:
• The array nums is 0-indexed.
• The integers lower and upper are inclusive and must satisfy lower <= upper.
Input: Example 1:
Explanation: Given the array nums = [0,1,7,4,4,5], lower = 3, upper = 6, we can form 6 valid pairs. The pairs are: (0,3), (0,4), (0,5), (1,3), (1,4), and (1,5).

Input: Example 2:
Explanation: Given the array nums = [1,7,9,2,5], lower = 11, upper = 11, there is only one valid pair: (2,3), where the sum of nums[2] + nums[3] equals 11.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus