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 nums and a number target. Count the pairs of positions i and j, with i before j (i < j), where nums[i] + nums[j] is less than target, and return that count.

Example 1
Input: nums = [-1, 1, 2, 3, 1], target = 2
Output: 3
Explanation: the pairs are (0, 1), (0, 2) and (0, 4), with sums 0, 1 and 0.
Example 2
Input: nums = [-6, 2, 5, -2, -7, -1, 3], target = -2
Output: 10
Solution

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 only makes sure each pair is counted once, not a second time the other way round. So we can lay the cards out from smallest to largest: -1, 1, 1, 2, 3.

Now put one marker, lo, on the smallest number and another, hi, on the largest, and add the two numbers they point at. Look at the picture below.

The sorted numbers -1, 1, 1, 2, 3 with target 2. First lo is on -1 and hi on 3: the sum 2 is not less than 2, so hi moves left. Then lo is on -1 and hi on 2: the sum 1 is less than 2, so -1 fits with 1, 1 and 2, and 3 pairs are counted at once.

In the first row, lo is on -1 and hi on 3. Their sum is 2, which is not less than 2. Since -1 is the smallest number of all, 3 is too big to fit with any other number either. So 3 drops out, and hi moves left.

In the second row, hi is on 2, and -1 + 2 = 1 fits. Every number between the two markers is no bigger than 2, so -1 fits with each of them too: with 1, with the other 1, and with 2. That is three pairs, counted in one step without checking them one by one.

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. For n numbers that checks n(n - 1)/2 pairs: 499,500 of them for 1,000 numbers.

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? lo starts at the first position and hi at the last. While lo is left of hi, compare the sum of their two numbers with target. If the sum is smaller, the number at lo fits with every number from position lo + 1 to hi. That is hi - lo pairs, so add them to the count and move lo right. Otherwise, move hi left.

Neither move loses a pair. The number at lo is the smallest still in range, so a number at hi that does not fit with it fits with nothing. And when lo moves on, its number has been counted with every number up to hi, while the numbers right of hi were already ruled out. The pairs counted in one step all include the number at lo, so no pair is counted twice.

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>, and a list made with List.of(...) cannot be changed: sorting it throws UnsupportedOperationException. Copying the numbers into an int array first avoids that, and also leaves the caller's list in its original order.

Java Solution

The method countPairs works in these steps:

  1. First, copy the numbers into an int array a with nums.stream().mapToInt(Integer::intValue).toArray(), and sort it with Arrays.sort(a).
  2. Set the two markers: lo to 0, the first position, and hi to a.length - 1, the last. Start the counter count at 0.
  3. While lo < hi, compare a[lo] + a[hi] with target. If the sum is smaller, add hi - lo to count and move lo right.
  4. Otherwise, move hi left.
  5. When the markers meet, return count.

The main method runs both examples, a list where every pair fits, a list where every sum equals the target, and a list with a single number.

Java
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:

Output
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] with target 100, where every pair fits. There the counting goes 3 + 2 + 1: the 1 at lo fits with all three numbers to its right, then the 2 with two, then the 3 with one.

The first 0 comes from [5, 5, 5] with target 10. Each sum is exactly 10, and the problem asks for less than target, so hi moves left until the markers meet. The last 0 is the single number 7, which makes no pair, so the while loop never runs.

Adding hi - lo, not 1, is what makes the count right. With count++ in place of count += hi - lo, each step counts only one pair, and the first two lines print 1 and 3 instead of 3 and 10.

Complexity

The work is the sort, plus one pass of lo and hi toward each other.

  • Time: O(n log n), where n is the number of values in nums. 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²).
  • Space: O(n) for the array a, the sorted copy of all n numbers. The markers and the counter add only O(1).

The same marker moves find one pair with an exact sum in Two Sum II.