![]() |
VOOZH | about |
Given four arrays containing integer elements and an integer sum, the task is to count the quadruplets such that each element is chosen from a different array and the sum of all the four elements is equal to the given sum.
Examples:
Input: P[] = {0, 2}, Q[] = {-1, -2}, R[] = {2, 1}, S[] = {2, -1}, sum = 0
Output: 2
(0, -1, 2, -1) and (2, -2, 1, -1) are the required quadruplets.
Input: P[] = {1, -1, 2, 3, 4}, Q[] = {3, 2, 4}, R[] = {-2, -1, 2, 1}, S[] = {4, -1}, sum = 3
Output: 10
Approach: We pick any two arrays and calculate all possible sums and and keep their counts in a map. Using the remaining two arrays, we calculate all possible sums and check how many times their additive inverse exists in the map which will be the count of required quadruplets.
Below is the implementation of the above approach:
2
Time Complexity : O(n1*n2+n3*n4) where, n1, n2, n3, n4 are size of arrays arr1, arr2, arr3 and arr4 respectively.
Auxiliary Space : O(n) , to store the elements in map.