4-sum problem: Given an unsorted integer array, check if it contains four elements tuple (quadruplets) having a given sum.

For example,

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

Practice this problem

1. Naive Recursive Approach

The idea is similar to the 0–1 Knapsack problem and uses recursion. For each item, either consider it or exclude it and recur for the remaining items. Return true if the desired sum is found by including or excluding the current item.

This approach is demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

Quadruplet exists

Java


Download  Run Code

Output:

Quadruplet exists

Python


Download  Run Code

Output:

Quadruplet exists

The time complexity of the above solution is exponential and requires additional space for the recursion (call stack). We can also use four nested loops and consider every quadruplet in the given array to check if the desired sum is found. This can reduce the time complexity to O(n4) for the input of n elements and doesn’t require any extra space.

2. Efficient solution using Hashing

The idea is to consider every pair of elements in the array one by one and insert it into a hash table. For each pair of elements (i, j), calculate the remaining sum. If the remaining sum exists in the map and elements involved in the previous occurrence doesn’t overlap with the current pair, i.e., (i, j, i, y) or (i, j, x, i) or (i, j, j, y), or (i, j, x, j), print the quadruplet and return.

Following is the C++, Java, and Python program that demonstrates it:

C++


Download  Run Code

Output:

Quadruplet Found (4, 0, 7, 9)

Java


Download  Run Code

Output:

Quadruplet Found (4, 0, 7, 9)

Python


Download  Run Code

Output:

Quadruplet Found (4, 0, 7, 9)

The time complexity of the above solution is O(n3) and requires O(n2) extra space, where n is the size of the input.

 
Also See:

Print all quadruplets with a given sum | 4 sum problem extended