4Sum II

Given four integer arrays nums1, nums2, nums3 and nums4, all of length n, return the number of tuples (i, j, k, l) such that 0 <= i, j, k, l < n and nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0.

30:00

4Sum II
medium
Free written solution
Topics
Companies

Given four integer arrays nums1, nums2, nums3 and nums4, all of length n, return the number of tuples (i, j, k, l) such that 0 <= i, j, k, l < n and nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0.

Example 1:
Input: {"nums1":[1,2],"nums2":[-2,-1],"nums3":[-1,2],"nums4":[0,2]}
Output: 2
Constraints:
  • n==nums1.length==nums2.length==nums3.length==nums4.lengthn == \text{nums1.length} == \text{nums2.length} == \text{nums3.length} == \text{nums4.length}

  • 1≤n≤2001 \leq n \leq 200

  • −228≤nums1[i],nums2[i],nums3[i],nums4[i]≤228-2^{28} \leq \text{nums1}[i], \text{nums2}[i], \text{nums3}[i], \text{nums4}[i] \leq 2^{28}

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums1":[1,2],"nums2":[-2,-1],"nums3":[-1,2],"nums4":[0,2]}

Split the four arrays into two halves. Every a + b from nums1 and nums2 goes into a count map; then every c + d looks for its opposite.

half 1: a + b (nums1 × nums2)

a\b
-2
-1
1
2

half 2: hits for -(c + d) (nums3 × nums4)

c\d
0
2
-1
2

count map: a + b → how many pairs (0 keys)

empty

tuples with a + b + c + d = 0:

0

Variables
VariableValue
map size0
total0
DepthFunction Call
Stack empty
0/10