4Sum II (LeetCode 454): Solution and Explanation

Medium
Array
Hash Table

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

  1. Create an empty map count from sum to number of pairs.
  2. For every a in nums1 and every b in nums2, increment count[a + b].
  3. Set total = 0.
  4. For every c in nums3 and every d in nums4, add count[-(c + d)] (0 if missing) to total.
  5. Return total.

Step-by-step example

nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2]
  1. 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}.
  2. c = -1, d = 0: c + d = -1, need 1. The map has 1, so total = 1.
  3. c = -1, d = 2: c + d = 1, need -1. The map has 1, so total = 2.
  4. c = 2, d = 0: c + d = 2, need -2. Missing, total stays 2.
  5. 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 total
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n^2)

Each half visits n * n pairs, and every map update or lookup is O(1) on average.

Space

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.