VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-of-quadruplets-with-given-sum/

⇱ Count of quadruplets with given Sum from 4 Arrays - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count of quadruplets with given Sum from 4 Arrays

Last Updated : 23 Sep, 2024

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:
(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: Generate all possible quadruplets and calculate the sum of every quadruplet. Count all such quadruplets whose sum is equal to the given sum.


Below is the implementation of the above approach:  


Output
2

Time Complexity: O(n4
Space Complexity: O(1)

Efficient Approach: Store frequency of all possible sum of two elements from two different arrays in a map. Iterate over other two arrays and find the sum of any two elements in these two arrays,lets it be cur_sum. If sum - cur_sum is present in the map, this means that there exists four elements in four different arrays whose sum is equal to sum.  

Implementation of the above approach:


Output
2

Time Complexity: O(n*n)

Auxiliary Space: O(n*n)

Comment
Article Tags: