takeuforward.org/data-structure/4-sum-find-quads-that-add-up-to-a-target-value/
1 Users
0 Comments
11 Highlights
0 Notes
Tags
Top Highlights
Inside the loop, we will first check if the current and the previous element is the same and if it is we will do nothing and continue to the next value of i.
Brute Force Approach
find unique quads that add up to give a target
Better Approach
Optimal Approach
get rid of two things i.e. the HashSet we were using for the look-up operation and the set data structure used to store the unique quadruplets.
To get the quadruplets in sorted order, we will sort the entire array in the first step and to get the unique quads, we will simply skip the duplicate numbers while moving the pointers.
As the entire array is sorted, the duplicate numbers will be in consecutive places
How to skip duplicate numbers:
If the sum is greater, then we need lesser elements and so we will decrease the value of l. If the sum is lesser than the target, we need a bigger value and so we will increase the value of k. If the sum is equal to the target, we will simply insert the quad i.e. nums[i], nums[j], nums[k], and nums[l] into our answer and move the pointers k and l skipping the duplicate elements.
we will again check for duplicate elements and only perform any further operation if the elements are different
Glasp is a social web highlighter that people can highlight and organize quotes and thoughts from the web, and access other like-minded people’s learning.