Friday, July 30, 2021

4Sum equal Target

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, and d are distinct.
nums[a] + nums[b] + nums[c] + nums[d] == target
You may return the answer in any order.

Constraints:
1 <= nums.length <= 200
-109 <= nums[i] <= 109
-109 <= target <= 109

Example,

Input: nums = [1,0,-1,0,-2,2], target = 0
Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]

Input: nums = [2,2,2,2,2], target = 8
Output: [[2,2,2,2]], there are three quadruplets possible, but we have to print unique quadruplets.

Approach:
Again this problem is similar to previous all 3Sum problems, This problem also can be solved using the "Two Pointers" method.
let's try to visualize,

We saw that constraints are very low nearly 200, but we can't solve this problem in  O(n^4) approach, but we can solve this problem easily in O(n^3) approach. Initially, we target the first sum of two values,

then using the two pointers we will search for another sum of two values. Thats how we can solve this problem, simply after checking our current target we can move our pointers. See the code for a better understanding.

Here, we have to handle another case, since we have to print unique 
quadruplets, so we can use a set vector for using all quadruplets, then simply we can push it to a 2D vector.


No comments:

Post a Comment