4Sum II (LeetCode 454): Solution and Explanation
Four arrays of the same length n are given. Count how many ways you can pick one number from each array so the four numbers add up to 0.
Intuition
Checking every tuple means n^4 combinations, which is 1.6 billion for n = 200. That is far too many.
The four arrays play separate roles, so split them into two pairs. The condition a + b + c + d = 0 is the same as a + b = -(c + d). If we knew, for every possible value, how many (a, b) pairs produce it, each (c, d) pair could be answered with a single lookup.
So first walk all n^2 pairs of the first two arrays and count their sums in a hash map. Then walk all n^2 pairs of the last two arrays and add up count[-(c + d)]. Two n^2 passes replace one n^4 search.
Approach: Meet in the middle with a count map
- Create an empty map
countfrom sum to number of pairs. - For every
ainnums1and everybinnums2, incrementcount[a + b]. - Set
total = 0. - For every
cinnums3and everydinnums4, addcount[-(c + d)](0 if missing) tototal. - Return
total.
Step-by-step example
nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2]
- Sums of the first half: 1 + (-2) = -1, 1 + (-1) = 0, 2 + (-2) = 0, 2 + (-1) = 1. The map is {-1: 1, 0: 2, 1: 1}.
- c = -1, d = 0: c + d = -1, need 1. The map has 1, so total = 1.
- c = -1, d = 2: c + d = 1, need -1. The map has 1, so total = 2.
- c = 2, d = 0: c + d = 2, need -2. Missing, total stays 2.
- c = 2, d = 2: c + d = 4, need -4. Missing, so the answer is 2.
Code: Python, Java, C++
1class Solution:
2 def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
3 count = defaultdict(int)
4 for a in nums1:
5 for b in nums2:
6 count[a + b] += 1
7 total = 0
8 for c in nums3:
9 for d in nums4:
10 total += count.get(-(c + d), 0)
11 return total1class Solution {
2 public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
3 Map<Integer, Integer> count = new HashMap<>();
4 for (int a : nums1) {
5 for (int b : nums2) {
6 count.merge(a + b, 1, Integer::sum);
7 }
8 }
9 int total = 0;
10 for (int c : nums3) {
11 for (int d : nums4) {
12 total += count.getOrDefault(-(c + d), 0);
13 }
14 }
15 return total;
16 }
17}1class Solution {
2public:
3 int fourSumCount(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3, vector<int>& nums4) {
4 unordered_map<int, int> count;
5 for (int a : nums1) {
6 for (int b : nums2) {
7 count[a + b]++;
8 }
9 }
10 int total = 0;
11 for (int c : nums3) {
12 for (int d : nums4) {
13 auto it = count.find(-(c + d));
14 if (it != count.end()) total += it->second;
15 }
16 }
17 return total;
18 }
19};Time and space complexity
O(n^2)
Each half visits n * n pairs, and every map update or lookup is O(1) on average.
O(n^2)
In the worst case all n^2 sums a + b are different, and each needs its own map entry.
Other approaches
Brute force over all tuples (time O(n^4), space O(1))
Four nested loops check every (i, j, k, l). Correct but hopeless for n = 200.
Three loops plus a map of nums4 (time O(n^3), space O(n))
Count the values of nums4, then loop over a, b and c and look up -(a + b + c). Better than brute force but still cubic.
Sorted pair sums with two pointers (time O(n^2 log n), space O(n^2))
Build both lists of pair sums, sort them, and walk one from the start and the other from the end, multiplying run lengths of equal values. It avoids hashing at the cost of a sort.
Common mistakes
- Storing only whether a sum exists instead of how many pairs produce it. Repeated sums must each count, so the map needs counts.
- Looking up c + d instead of -(c + d). The two halves must cancel out.
- Counting distinct value tuples. The problem counts index tuples, so equal values at different indexes are separate answers.
- Using the count map for nums3 and nums4 too. Only one half goes into the map; the other half is only looked up.
Frequently asked questions
Why split the arrays two and two instead of one and three?
A one and three split still needs n^3 work for the three-array side. Two and two makes both sides n^2, which balances the work.
Can the sums overflow?
Each value is at most 2^28 in absolute value, so a + b fits easily in 32 bits. The answer itself is at most 200^4 = 1.6 * 10^9, which also fits in a signed 32-bit integer.
How is this different from 4Sum?
4Sum picks four distinct indexes from one array and asks for distinct value quadruplets, which needs sorting and duplicate skipping. 4Sum II picks one index from each of four arrays and asks only for a count, so hashing pair sums is enough.