You are given an array ‘NUMS’ of length ‘N’. You are also given an integer ‘TARGET’.
Return an array of all the unique quadruplets [ ‘NUMS[ a ]’, ‘NUMS[ b ]’, ‘NUMS[ c ]’, ‘NUMS[ d ]’ ] with the following conditions:
i. 0 <= a, b, c, d < ‘N’ and a, b, c, and d are distinct.
ii. NUMS[ a ] + NUMS[ b ] + NUMS[ c ] +NUMS[ d ] = TARGET
Return the array in any order.
(NUMS[ a ], NUMS[ b ], NUMS[ c ], NUMS[ d ]), (NUMS[ a ], NUMS[ d ], NUMS[ c ], NUMS[ b ]), (NUMS[ a ], NUMS[ c ], NUMS[ b ], NUMS[ d ])... all of them are treated or considered the same quadruplets.
Two quadruplets are different if there is any integer in one quadruplet which is not in the other.
The solution will be verified by the number of valid quadruplets returned. In the output, only the number of valid quadruplets will be printed.
Input: ‘N’ = 5, ‘TARGET’ = 5, ‘NUMS’ = [ 1, 2, 1, 0, 1 ]
Output: 1.
There is only one unique quadruplet with sum = 5 and that is [1, 2, 1, 1].
The first line contains two integers, ‘N’ and ‘TARGET’, denoting the length of the array ‘NUMS’ and an arbitrary integer.
The second line contains ‘N’ space-separated integers.
Output format :
Prints the number of unique quadruplets.
Note :
You don't need to print anything. It has already been taken care of. Just implement the given function.
6 8
2 2 2 2 1 3
2
(2+2+2+2) = (2+2+1+3) = 4.
4 4
1 1 1 0
0
4 <= N <= 100
-10^6 <= NUMS[ i ] <= 10^6
-10^6 <= TARGET <= 10^6
Time Limit: 1 sec
Can you think of a way to generate all possible quadruplets with a sum equal to target and store the unique ones only?
In this approach, We can run 4 nested loops to generate all possible quadruplets. In order to remove duplicate quadruples we can use a set. There is still one problem if the quadruples are like (a, b, c, d) and (a, d, b, c) set will not treat them as the same. To solve this problem we can sort the whole array ‘NUMS’.
The steps are as follows:-
function fourSum( [ int ] nums, int target):
O( N^4 * log( N ) ), Where ‘N’ is the length of array ‘NUMS’.
We are running 4 nested loops and for each quadruple, we are inserting it into the set which has a time complexity of O( log( N ) ).
Hence the time complexity is O( N^4 * log( N ) ).
O( N^4 ). Where ‘N’ is the length of array ‘NUMS’.
We are using a set to store all unique quadruplets. In the worst case, there can be ‘N’^4 quadruplets.
Hence space complexity is O( N^4 ).