4Sum II

Count the ways to pick one number from each of four arrays so that the four add up to 0.

You are given four integer arrays nums1, nums2, nums3 and nums4, all of the same length n. Pick one position from each array: i in nums1, j in nums2, k in nums3 and l in nums4. Return how many of these choices (i, j, k, l) give nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0. Choices are told apart by their positions, so equal numbers at different positions count separately. Every number lies between -228 and 228.

Example 1
Input: nums1 = [1, 2], nums2 = [-2, -1], nums3 = [-1, 2], nums4 = [0, 2]
Output: 2
Explanation: 1 + (-2) + (-1) + 2 = 0 and 2 + (-1) + (-1) + 0 = 0.
Example 2
Input: nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0]
Output: 1
Solution

The Idea

Picture four bags of number cards, one bag for each array. You take one card from each bag and add up the four numbers. How many ways of taking the cards give 0? In Example 1 every bag holds two cards, so there are 2 × 2 × 2 × 2 = 16 ways. Two of them add up to 0: 1, -2, -1 and 2, then 2, -1, -1 and 0.

Trying all 16 ways is quick. With 200 cards in each bag, though, there are 2004 ways, which is 1.6 billion. Can we count the ways that give 0 without looking at every one of them?

Split the four cards into two halves: a from nums1 and b from nums2, then c from nums3 and d from nums4. The four add up to 0 exactly when a + b is the opposite of c + d, that is, a + b = -(c + d). So for each pair c, d, we only need to know how many pairs a, b have the sum -(c + d). And those pairs can be counted once, before looking at c and d at all. Look at the picture below.

Left: the sums a + b of nums1 and nums2 with their counts: -1 once, 0 twice, 1 once. Right: each pair c + d from nums3 and nums4 and the sum it needs. -1 + 0 needs 1 and adds 1, -1 + 2 needs -1 and adds 1, the other two add 0, so the count is 2.

On the left are the four sums a + b of the first two arrays: 1 + (-2) = -1, 1 + (-1) = 0, 2 + (-2) = 0 and 2 + (-1) = 1. The sum 0 is made twice, so its count is 2. On the right, each pair from the last two arrays works out the sum it needs. The first row, -1 + 0 = -1, needs 1. One pair on the left makes 1, so this row adds 1.

The second row, -1 + 2 = 1, needs -1 and adds 1 as well. The last two rows need -2 and -4, which no pair on the left makes, so they add 0. The count is 1 + 1 + 0 + 0 = 2, the answer of Example 1.

So one big search of four cards becomes two small jobs over pairs: count the sums of the first two arrays, then look up what each pair of the last two arrays needs. Splitting a search into two halves that are joined in the middle like this is called meet in the middle.

Solution Approach

Turning that idea into code means settling three things: where to keep the sums of the first two arrays, why each sum needs a count, and whether the sums fit in an int.

Keeping the sums of the first two arrays

Where do the sums a + b go, so that each lookup is quick? Into a HashMap, Java's table from keys to values, which finds a key in about one step however many keys it holds. Here the key is the sum. Keeping the sums in a plain list would mean scanning up to n2 sums for each of the n2 pairs c, d, which is n4 steps again.

Counting pairs, not just sums

Why does the map store a count for each sum, and not only the fact that the sum exists? Every pair a, b with the needed sum gives a different choice of positions, and each choice is counted. In Example 1 the sum 0 is made by two pairs, so a pair c, d that needed 0 would complete two choices and add 2.

Sums that fit in an int

Can the additions go wrong? A Java int holds values up to 2,147,483,647, about 2.1 billion. An int that goes past its largest value continues from the most negative values, which is called overflow. Here every number is at most 228 = 268,435,456 in size, so a + b and c + d are at most 229, about 537 million. Plain int sums are safe; larger numbers would need long sums.

Java Solution

The method fourSumCount works in these steps:

  1. First, create the map pairSums, from a sum to the number of pairs that make it.
  2. Fill it with two loops, one inside the other: the outer loop takes each a from nums1, the inner loop each b from nums2. pairSums.merge(a + b, 1, Integer::sum) stores 1 the first time a sum appears, and adds 1 to its count after that.
  3. Set count to 0. Then two more loops, one inside the other, take each c from nums3 and each d from nums4.
  4. For each of these pairs, pairSums.getOrDefault(-(c + d), 0) gives the number of pairs from the first two arrays that make the needed sum, or 0 when there are none. Add it to count.
  5. When all the loops are done, return count.

The main method runs both examples, four copies of [-1, 1] where sums repeat, four copies of [1, 2] where nothing adds up to 0, and four numbers of size 228, the largest allowed.

Java
import java.util.HashMap;
import java.util.Map;

public class FourSumII {

    public static int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
        Map<Integer, Integer> pairSums = new HashMap<>();    // a + b -> how many pairs give it
        for (int a : nums1) {
            for (int b : nums2) {
                pairSums.merge(a + b, 1, Integer::sum);
            }
        }
        int count = 0;
        for (int c : nums3) {
            for (int d : nums4) {
                count += pairSums.getOrDefault(-(c + d), 0);   // pairs that cancel c + d
            }
        }
        return count;
    }

    public static void main(String[] args) {
        System.out.println(fourSumCount(new int[] {1, 2}, new int[] {-2, -1},
                new int[] {-1, 2}, new int[] {0, 2}));
        System.out.println(fourSumCount(new int[] {0}, new int[] {0},
                new int[] {0}, new int[] {0}));
        int[] signs = {-1, 1};
        System.out.println(fourSumCount(signs, signs, signs, signs));
        int[] small = {1, 2};
        System.out.println(fourSumCount(small, small, small, small));
        int big = 1 << 28;                                    // 268,435,456
        System.out.println(fourSumCount(new int[] {big}, new int[] {big},
                new int[] {-big}, new int[] {-big}));
    }
}

Running it prints:

Output
2
1
6
0
1

The first two lines, 2 and 1, answer the two examples. The third line comes from four copies of [-1, 1]. A choice adds up to 0 when two of its numbers are -1 and two are 1, and there are 6 ways to pick which two arrays give the -1. In pairSums, -2 and 2 have the count 1, and 0 has the count 2, because -1 + 1 and 1 + (-1) both make it. The four pairs from the last two arrays add 1, 2, 2 and 1, which is 6. A version that keeps only a Set of the sums adds at most 1 per lookup, and prints 4 for this input.

The fourth line is 0, because numbers that are all 1 or more can never add up to 0. The last line is 1: a + b is 536,870,912, and -(c + d) is the same value, both well inside the range of an int.

Complexity

The work is two passes over pairs: one over the pairs of the first two arrays, and one over the pairs of the last two.

  • Time: O(n2), where n is the length of each array. Each pass looks at n × n pairs and does one map step for each, which takes O(1) on average. That is 2n2 steps, compared with n4 for trying every choice.
  • Space: O(n2) for pairSums. When all n2 sums a + b differ, each one gets its own entry. The second pass stores nothing.

When the four numbers come from a single array and the groups themselves must be listed, each only once, see 4Sum.