Count Pairs Whose Sum is Less Than Target
Count the pairs of numbers in a list whose sum is less than a target, without checking every pair.
You are given a list of integers numstargetijiji < jnums[i] + nums[j]target
Example 1
Output: 3
Explanation: the pairs are (0, 1), (0, 2) and (0, 4), with sums 0, 1 and 0.
Example 2
Output: 10
The Idea
Picture five number cards on a table: -1, 1, 2, 3 and 1. You pick any two of them and add them up. How many picks give less than 2? Five cards allow 10 different picks, and only three of them work. All three use -1: -1 with 1, -1 with 2, and -1 with the other 1.
Checking all 10 picks is easy here, but the number of picks grows fast: 1,000 numbers already make 499,500 pairs. Can we count the pairs that fit without looking at each one?
First, notice that the order of the cards does not matter for the count. The rule i < j
Now put one marker, lohi
In the first row, lohihi
In the second row, hi
So each comparison does one of two things. Either it counts every pair of the smallest number at once, or it rules out the largest number. Searching with two markers that start at opposite ends and move toward each other is called the two-pointer technique.
Solution Approach
Turning that idea into code means settling three things: why to sort, when each marker moves, and how to sort without changing the list we are given.
Sorting the numbers
Why sort at all? The simple way is two loops, one inside the other, that try every pair and count the sums below target
Sorting moves the numbers to new positions, but every two numbers still form one pair, just at other positions. So the count stays the same. Once the numbers are in order, the two markers can count all the pairs in a single pass.
Moving the two markers
When does each marker move? lohilohitargetlolo + 1hihi - lolohi
Neither move loses a pair. The number at lohilohihilo
Each step moves one marker by one place, so the markers meet after at most n - 1 steps.
Keeping the given list unchanged
Can we sort the list we are given? The method receives a List<Integer>List.of(...)UnsupportedOperationExceptionint
Java Solution
The method countPairs
- First, copy the numbers into an
arrayint witha , and sort it withnums.stream().mapToInt(Integer::intValue).toArray() .Arrays.sort(a) - Set the two markers:
to 0, the first position, andlo tohi , the last. Start the countera.length - 1 at 0.count - While
, comparelo < hi witha[lo] + a[hi] . If the sum is smaller, addtarget tohi - lo and movecount right.lo - Otherwise, move
left.hi - When the markers meet, return
.count
The main
import java.util.Arrays;
import java.util.List;
public class CountPairsWhoseSumLessThanTarget {
public static int countPairs(List<Integer> nums, int target) {
int[] a = nums.stream().mapToInt(Integer::intValue).toArray();
Arrays.sort(a);
int lo = 0;
int hi = a.length - 1;
int count = 0;
while (lo < hi) {
if (a[lo] + a[hi] < target) {
count += hi - lo; // a[lo] pairs with every position lo+1 .. hi
lo++;
} else {
hi--; // a[hi] is too big to pair with anything left
}
}
return count;
}
public static void main(String[] args) {
System.out.println(countPairs(List.of(-1, 1, 2, 3, 1), 2));
System.out.println(countPairs(List.of(-6, 2, 5, -2, -7, -1, 3), -2));
System.out.println(countPairs(List.of(1, 2, 3, 4), 100)); // every pair fits
System.out.println(countPairs(List.of(5, 5, 5), 10)); // sums equal target
System.out.println(countPairs(List.of(7), 10)); // no pair at all
}
}
Running it prints:
3
10
6
0
0
The 3 and the 10 at the top match the answers of Example 1 and Example 2. The 6 comes from [1, 2, 3, 4]lo
The first 0 comes from [5, 5, 5]targethiwhile
Adding hi - locount++count += hi - lo
Complexity
The work is the sort, plus one pass of lohi
- Time: O(n log n), where n is the number of values in
. The sort takes O(n log n), and the pass takes at most n - 1 steps, because each step moves one marker by one place. Trying every pair with two loops would take O(n²).nums - Space: O(n) for the array
, the sorted copy of all n numbers. The markers and the counter add only O(1).a
The same marker moves find one pair with an exact sum in