![]() |
VOOZH | about |
Given an array arr[], and an integer target, find all possible uniquequadruplets in an array whose sum is equal to the given target value. We can return quadruplets in any order, but all the quadruplets should be internally sorted, i.e., for any quadruplets [q1, q2, q3, q4] the following should follow: q1 <= q2 <= q3 <= q4.
Examples:
Input: arr[] = [10, 11, 10, 12, 11], target = 43
Output: [[10, 10, 11, 12]]
Explanation: The quadruplets are:
[10, 11, 10, 12], sum = 10 + 11 + 10 +12 = 43
[10, 11, 10, 11], sum = 10 + 11 + 10 + 11 = 42
[10, 11, 12, 11], sum = 10 + 11 + 12 + 11 = 44
[10, 10, 12, 11], sum = 10 + 10 + 12 + 11 = 43
[11, 10, 12, 11], sum = 11 + 10 + 12 + 11 = 44
When arranged in sorted order, there is only one distinct quadruplet with sum = 43, that is [10, 10, 11, 12]Input: arr[] = [10, 2, 3, 4, 5, 7, 8], target = 23
Output: [[2, 3, 8, 10], [2, 4, 7, 10], [3, 5, 7, 8]]
Explanation: There are only three distinct quadruplets with sum = 23.
Input: arr[] = [1, 1, 1, 1, 1, 1], target = 4
Output: [[1, 1, 1, 1]]
We have discussed how to find if a quadruple with given sum exists or not in an array. We are going to extend the ideas here to find all distinct Quadruplets.
Table of Content
We run 4 nested loops to generate all quadruplets. For every quadruple, we check if its sum is equal to the given target. If yes, then we first sort it to match the question requirements, then we check if this is a duplicate or not. If it is a new quadruple, we add it to the result.
2 3 8 10 2 4 7 10 3 5 7 8
We mainly generate all pairs and for every pair, we use hashing to find the remaining two pairs.
We mainly use hashing at two places.
2 3 8 10 2 4 7 10 3 5 7 8
- Sort the array
- Generate all pairs. For every pair, find the remaining two elements using two pointer technique.
How do we ensure that we get only distinct ? While generating pairs, we skip duplicates in both outer and inner loops by comparing with the previous element (note that the array is sorted first). In two Pointer technique, when we find a match, we skip all occurrences of that element in the array.
2 3 8 10 2 4 7 10 3 5 7 8
Further Optimizations: