Given four integer arrays, count the number of quadruplets with a zero sum, including exactly one element from each array.

For example,

Input:
 
A = [0, -1, 1]
B = [-1]
C = [2, 4]
D = [-4, 0]
 
Output: 2
 
Explanation: There are two quadruplets with a zero sum, as follows:
 
A[1] + B[0] + C[0] + D[1] = [-1 + -1 + 2 + 0]
A[2] + B[0] + C[1] + D[0] = [ 1 + -1 + 4 + -4]

The problem of finding the quadruplet A[i] + B[j] + C[k] + D[l] = 0 can be broken down into finding the pair (A[i] + B[j]) that equals -(C[k] + D[l]). The idea is to loop through the elements of the first two arrays. For each pair, calculate their sum and keep track of sum-count mappings in a hash table. Next, calculate the sum of each pair in the other two arrays. If the opposite sum exists in the hash table, we have found a quadruplet.

 
The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

2

Java


Download  Run Code

Output:

2

Python


Download  Run Code

Output:

2

The time complexity of the above solution is O(n2) and requires O(n2) extra space, where n is the size of the input.