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 nums1nums2nums3nums4inums1jnums2knums3lnums4(i, j, k, l)nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0
Example 1
Output: 2
Explanation: 1 + (-2) + (-1) + 2 = 0 and 2 + (-1) + (-1) + 0 = 0.
Example 2
Output: 1
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: anums1bnums2cnums3dnums4a + bc + da + b = -(c + d)cdab-(c + d)cd
On the left are the four sums a + b
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 + bHashMapcd
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 abcd
Sums that fit in an int
Can the additions go wrong? A Java intinta + bc + dintlong
Java Solution
The method fourSumCount
- First, create the map
, from a sum to the number of pairs that make it.pairSums - Fill it with two loops, one inside the other: the outer loop takes each
froma , the inner loop eachnums1 fromb .nums2 stores 1 the first time a sum appears, and adds 1 to its count after that.pairSums.merge(a + b, 1, Integer::sum) - Set
to 0. Then two more loops, one inside the other, take eachcount fromc and eachnums3 fromd .nums4 - For each of these pairs,
gives the number of pairs from the first two arrays that make the needed sum, or 0 when there are none. Add it topairSums.getOrDefault(-(c + d), 0) .count - When all the loops are done, return
.count
The main[-1, 1][1, 2]
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:
2
1
6
0
1
The first two lines, 21[-1, 1]pairSumsSet
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-(c + d)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
. When all n2 sumspairSums differ, each one gets its own entry. The second pass stores nothing.a + b
When the four numbers come from a single array and the groups themselves must be listed, each only once, see