Problem
Given an array nums
of n
integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]]
such that:
0 <= a, b, c, d < n
a
,b
,c
, andd
are distinct.nums[a] + nums[b] + nums[c] + nums[d] == target
You may return the answer in any order.
Similar Problem on Pramp
Your function should return an array of these numbers in an ascending order. If such a quadruplet doesn’t exist, return an empty array.
Note that there may be more than one quadruplet in arr
whose sum is s
. You’re asked to return the first one you encounter (considering the results are sorted).
Examples
Example 1:
|
|
Example 2:
|
|
Solution
In Two Sum, we had a problem with sorting as we could have solved hte problem in O(n) time using hashmap. But here we already have O(n^3) if we use hash. So, we can sort.
We can also use solutions like 3Sum - Classic and Two Sum as well.
Also, we can implement kSum
Method 1 - Sorting
Algorithm
- Sort the array
- Run 1 outer loop from
0
ton-3
- Run inner loop from
n-1
to2
- Runner inner most loop using 2 pointers
l
andr
, l =i+1
, r=j-1
- Continue finding the quads till we are out of loops
Duplicates needs to handled.
Code
|
|
Method 2 - Using kSum
We can use generic kSum.
Code
|
|
Complexity
- ⏰ Time complexity:
O(n^3)
- 🧺 Space complexity:
O(1)