Skip to content
Problem 454 · LeetCode 454(opens in a new tab)

4Sum II

MediumArrays

You are given four lists of whole numbers, nums1, nums2, nums3 and nums4, all of the same length n.

Count the ways to pick one position from each list, i from nums1, j from nums2, k from nums3 and l from nums4, so that the four chosen values add up to exactly 0. Different positions count as different picks even when the values are the same.

Example 1

Input:  nums1 = [1, -3], nums2 = [2, 0], nums3 = [0, 1], nums4 = [-1, 2]
Output: 2
Why:    1 + 0 + 0 + (−1) = 0 and (−3) + 0 + 1 + 2 = 0
2 more examples and the constraints

Example 2

Input:  nums1 = [3], nums2 = [1], nums3 = [-2], nums4 = [-2]
Output: 1
Why:    the only pick: 3 + 1 − 2 − 2 = 0

Example 3

Input:  nums1 = [1], nums2 = [1], nums3 = [1], nums4 = [1]
Output: 0
Why:    the only pick sums to 4

Constraints

  • 1 ≤ n ≤ 200, and all four lists have length n
  • −2^28 ≤ every value ≤ 2^28

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Try every tupleO(n⁴)
  2. Pair sums in a mapO(n²)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for n = 200Verdict
Try every tupleO(n⁴)
Mention it, then move on
Pair sums in a mapO(n²)
Best; two passes over pairs

n = length of each list.

Edge cases to test

  • One number per list. [3], [1], [−2], [−2] is one tuple, and it works.
  • All zeros. Every tuple works: the answer is n⁴, which is 1,600,000,000 when n = 200 and still fits a 32-bit int.
  • Repeated values. Equal values at different positions are different picks, so each counts.
  • Values at the limits. Sums reach ±2^30 at most, which fits a 32-bit int.
  • No tuple at all. [1], [1], [1], [1] gives 0.

Common mistakes

  • Storing a set of sums instead of how often each sum appears, which undercounts repeats.
  • Looking up c + d instead of −(c + d).
  • Sorting and using two pointers like in 4Sum, which is built for one list and finding the picks, not counting across four.

How to talk through it

  1. 1Clarify. Do equal values at different positions count separately? Do you need the tuples or only how many?
  2. 2Give the brute force. Four loops, n⁴ tuples: 1.6 billion for n = 200.
  3. 3Split the sum. a + b = −(c + d), so pair up the lists in two halves and meet in the middle.
  4. 4Code the map. Count every a + b, then add sums[−(c + d)] for every (c, d).
  5. 5Test out loud. Run the single-element and all-zero cases before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?