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.
Prints the number of unique quadruplets.
You don't need to print anything. It has already been taken care of. Just implement the given function.
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’.
In this approach, the idea is to use two pointers to optimize the previous approach. We will first sort the array. We can iterate over the array ‘NUMS’ ( ‘i’ = 0…’N’-1) for variable ‘A’ then we can make a nested loop( ‘j’ = ‘i’ +1 to ‘N’ - 1) to iterate over ‘NUMS’ for variable ‘B’ and for variable ‘C’ and ‘D’ we will run only one loop. We will two pointers ‘LEFT’ and ‘RIGHT’ where ‘LEFT’ points to ‘NUMS[ j + 1]’ and ‘RIGHT’ points to the last element. Let us consider value of ‘NUMS[ left ] = ‘C’ and ‘NUMS[ right ] =’D’. Total = ‘A’ + ‘B’ + ‘C’ + ‘D’. If the total is equal to the target then we push it into the array and increment ‘LEFT’ by 1 and decrement ‘RIGHT’ by 1. Else if the total is greater than the target then we decrement ‘RIGHT’ by 1 else we increment ‘LEFT’ by 1.
To remove the duplicates, for each loop when we are incrementing the index we will keep on incrementing it till the value is the same. For example if ‘NUMS[ i ] = 4 then increment ‘i’ until ‘NUMS[ i ]’ != 4.