Given an unsorted integer array, print all distinct four elements tuple (quadruplets) in it, having a given sum.

For example,

Input:
 
A[] = [2, 7, 4, 0, 9, 5, 1, 3]
target = 20
 
Output: Below are the quadruplets with sum 20
 
(0, 4, 7, 9)
(1, 3, 7, 9)
(2, 4, 5, 9)

Practice this problem

In the previous post, we have discussed how to check if an array contains a quadruplet or not. In this post, we will print all distinct quadruplets present in an array.

 
We start by sorting the given array in ascending order and then for each pair (A[i], A[j]) in the array where i < j, check if a quadruplet is formed by the current pair and a pair from subarray A[j+1…n). Refer to this post to find pairs with a given sum in a sorted array in linear time.

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

C++


Download  Run Code

Output:

(0 4 7 9)
(1 3 7 9)
(2 4 5 9)

Java


Download  Run Code

Output:

(0 4 7 9)
(1 3 7 9)
(2 4 5 9)

Python


Download  Run Code

Output:

(0, 4, 7, 9)
(1, 3, 7, 9)
(2, 4, 5, 9)

The time complexity of the above solution is O(n3) and doesn’t require any extra space, where n is the size of the input.