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: Two different approaches to solve this problem has been discussed in Set 1 and Set 2 of this article. Here, an approach using the binary search will be discussed.
Pick any two arrays and calculate all the possible pair sums and store them in a vector. Now, pick the other two arrays and calculate all possible sums and for every sum say tempSum, check whether sum – temp exists in the vector created earlier (after sorting it) using the binary search.
Below is the implementation of the above approach:
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std; // Function to return the count // of the required quadruplets int countQuadruplets( int arr1[], int n1, int arr2[], int n2, int arr3[], int n3, int arr4[], int n4, int value) { vector< int > sum1; vector< int >::iterator it; vector< int >::iterator it2; int cnt = 0; // Take every possible pair sum // from the two arrays for ( int i = 0; i < n1; i++) { for ( int j = 0; j < n2; j++) { // Push the sum to a vector sum1.push_back(arr1[i] + arr2[j]); } } // Sort the sum vector sort(sum1.begin(), sum1.end()); // Calculate the pair sums from // the other two arrays for ( int i = 0; i < n3; i++) { for ( int j = 0; j < n4; j++) { // Calculate the sum int temp = arr3[i] + arr4[j]; // Check whether temp can be added to any // sum stored in the sum1 vector such that // the result is the required sum if (binary_search(sum1.begin(), sum1.end(), value - temp)) { // Add the count of such values from the sum1 vector it = lower_bound(sum1.begin(), sum1.end(), value - temp); it2 = upper_bound(sum1.begin(), sum1.end(), value - temp); cnt = cnt + ((it2 - sum1.begin()) - (it - sum1.begin())); } } } return cnt; } // Driver code int main() { int arr1[] = { 0, 2 }; int n1 = sizeof (arr1) / sizeof (arr1[0]); int arr2[] = { -1, -2 }; int n2 = sizeof (arr2) / sizeof (arr2[0]); int arr3[] = { 2, 1 }; int n3 = sizeof (arr3) / sizeof (arr3[0]); int arr4[] = { 2, -1 }; int n4 = sizeof (arr4) / sizeof (arr4[0]); int sum = 0; cout << countQuadruplets(arr1, n1, arr2, n2, arr3, n3, arr4, n4, sum); return 0; } |
2
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.