# Find all distinct quadruplets in an array that sum up to a given value

• Last Updated : 12 May, 2021

Given an array arr[] consisting of N integers and an integer K, the task is to print all possible unique quadruplets (arr[i], arr[j], arr[k], arr[l]) whose sum is K such that all their indices are distinct.

Examples:

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.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: arr[] = {1, 0, -1, 0, -2, 2}, K = 0
Output:
-2 -1 1 2
-2 0 0 2
-1 0 0 1
Explanation:
Below are the quadruplets whose sum is K (= 0):

• {-2, -1, 1, 2}
• {-2, 0, 0, 2}
• {-1, 0, 0, 1}

Input: arr[] = {1, 2, 3, -1}, target = 5
Output:
1 2 3 -1

Naive Approach: The simplest approach is to generate all possible quadruplets from the given array arr[] and if the sum of elements of the quadruplets is K, then insert the current quadruplets in the HashSet to avoid the count of duplicates quadruplets. After checking for all the quadruplets, print all the quadruplets stored in the HashSet.

Time Complexity: O(N4)
Auxiliary Space: O(N4)

Efficient Approach: The above approach can also be optimized by using the idea of generating all possible pairs of the given array. Follow the given steps to solve the problem:

• Initialize a HashMap, say ans that stores all the possible quadruplets.
• Initialize a HashMap, say M that stores the sum of all possible pairs of the given array with their corresponding indices.
• Generate all possible pairs of the given array and store the sum of all pairs of elements (arr[i], arr[j]) with their indices (i, j) in the HashMap M.
• Now, generate all possible pairs of the given array again and for each sum of all pairs of elements (arr[i], arr[j]) if the value (K – sum) exists in the HashMap M, then store the current quadruplets in the HashMap ans.
• After completing the above steps, print all the quadruplets stored in the HashMap ans.

Below is the implementation of the above approach:

## Java

 `// Java program for the above approach`` ` `import` `java.io.*;``import` `java.util.*;`` ` `public` `class` `GFG {`` ` `    ``// Stores the pair of indices``    ``static` `class` `Pair {`` ` `        ``int` `index1;``        ``int` `index2;`` ` `        ``// Constructor``        ``Pair(``int` `x, ``int` `y)``        ``{``            ``index1 = x;``            ``index2 = y;``        ``}``    ``}`` ` `    ``// Function to find the all the``    ``// unique quadruplets with the``    ``// elements at different indices``    ``public` `static` `void``    ``GetQuadruplets(ArrayList nums,``                   ``int` `target)``    ``{`` ` `        ``// Stores the sum mapped to``        ``// a List Of Pair``        ``HashMap > map``            ``= ``new` `HashMap<>();`` ` `        ``// Generate all possible pairs``        ``// for the HashMap``        ``for` `(``int` `i = ``0``;``             ``i < nums.size() - ``1``; i++) {`` ` `            ``for` `(``int` `j = i + ``1``;``                 ``j < nums.size(); j++) {`` ` `                ``// Find the sum of pairs``                ``// of elements``                ``int` `sum = nums.get(i)``                          ``+ nums.get(j);`` ` `                ``// If the sum doesn't``                ``// exists then update``                ``// with the new pairs``                ``if` `(!map.containsKey(sum)) {`` ` `                    ``ArrayList temp``                        ``= ``new` `ArrayList<>();``                    ``Pair p = ``new` `Pair(i, j);``                    ``temp.add(p);`` ` `                    ``// Update the hashmap``                    ``map.put(sum, temp);``                ``}`` ` `                ``// Otherwise, push the new``                ``// pair of indices to the``                ``// current sum``                ``else` `{`` ` `                    ``ArrayList temp``                        ``= map.get(sum);`` ` `                    ``Pair p = ``new` `Pair(i, j);``                    ``temp.add(p);`` ` `                    ``// Update the hashmap``                    ``map.put(sum, temp);``                ``}``            ``}``        ``}`` ` `        ``// Stores all the Quadruplets``        ``HashSet > ans``            ``= ``new` `HashSet >();`` ` `        ``for` `(``int` `i = ``0``;``             ``i < nums.size() - ``1``; i++) {`` ` `            ``for` `(``int` `j = i + ``1``;``                 ``j < nums.size(); j++) {`` ` `                ``int` `lookUp = target``                             ``- (nums.get(i)``                                ``+ nums.get(j));`` ` `                ``// If the sum with value``                ``// (K - sum) exists``                ``if` `(map.containsKey(lookUp)) {`` ` `                    ``// Get the pair of``                    ``// indices of sum``                    ``ArrayList temp``                        ``= map.get(lookUp);`` ` `                    ``for` `(Pair pair : temp) {`` ` `                        ``// Check if i, j, k``                        ``// and l are distinct``                        ``// or not``                        ``if` `(pair.index1 != i``                            ``&& pair.index1 != j``                            ``&& pair.index2 != i``                            ``&& pair.index2 != j) {`` ` `                            ``ArrayList values``                                ``= ``new` `ArrayList<>();``                            ``values.add(``                                ``nums.get(pair.index1));``                            ``values.add(``                                ``nums.get(pair.index2));``                            ``values.add(nums.get(i));``                            ``values.add(nums.get(j));`` ` `                            ``// Sort the list to``                            ``// avoid duplicacy``                            ``Collections.sort(values);`` ` `                            ``// Update the hashset``                            ``ans.add(values);``                        ``}``                    ``}``                ``}``            ``}``        ``}`` ` `        ``// Print all the Quadruplets``        ``for` `(ArrayList arr : ans) {``            ``System.out.println(arr);``        ``}``    ``}`` ` `    ``// Driver Code``    ``public` `static` `void` `main(String[] args)``    ``{``        ``ArrayList arr = ``new` `ArrayList<>();``        ``arr.add(``1``);``        ``arr.add(``0``);``        ``arr.add(-``1``);``        ``arr.add(``0``);``        ``arr.add(-``2``);``        ``arr.add(``2``);``        ``int` `K = ``0``;``        ``GetQuadruplets(arr, K);``    ``}``}`
Output:
```[-2, 0, 0, 2]
[-1, 0, 0, 1]
[-2, -1, 1, 2]
```

Time Complexity: O(N2 * log N)
Auxiliary Space: O(N2)

My Personal Notes arrow_drop_up