Solution: Count Pairs Whose Sum is Less than Target
Let's solve the Count Pairs Whose Sum is Less than Target problem using the Modified Binary Search pattern.
We'll cover the following
Statement
You are given a 0-indexed integer array, nums
, of length target
. Your task is to determine the number of distinct pairs of indices
(i.e., comes before in the array) The sum of the elements of the indices
, (i.e., ), is strictly less than target
.
Constraints:
nums.length
nums[i]
, target
Solution
The algorithm counts the number of valid pairs in an array using sorting and binary search. We can use binary search to find valid pairs by sorting the array first. The algorithm uses a binary search for each element to determine the range of subsequent elements that can form valid pairs with it. These valid pairs are then added to a running total count of pairs.
The steps of the algorithm are as follows:
Sort the input array
nums
in ascending order for binary search.A variable
count
is initialized toto keep track of the total number of valid pairs. The algorithm iterates through each element of the array (except the last one) using an index
, as pairs require . For each element nums[i]
:Set the binary search range with
low = i + 1
andhigh = len(nums)
.Perform binary search while
low < high
:Compute
mid = (low + high) / 2
.If
nums[i] + nums[mid] < target
:All elements in the range
satisfy the condition and are valid pairs. Move
low = mid + 1
to explore additional valid pairs.
Otherwise, reduce the range by setting
high = mid
to focus on smaller sum pairs.
All elements in the range
form valid pairs with nums[i]
. The number of valid pairs is calculated as:count = low − (i + 1)
.
Once all elements have been processed, return the
count
as the total number of valid pairs.
Let’s look at the following illustration to get a better understanding of the solution:
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.