Given an array
-
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.
Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
Output: [[2,2,2,2]]
Constraints:
-
1 <= nums.length <= 200 -
-109 <= nums[i] <= 109 -
-109 <= target <= 109
Contents
Solution 1 - Sort input array, and generalize into a K sum problem with the intution from 2 Sum, 3 Sum problems
In this approach, we are going to sort the input array first, then generalize the solutions that we have used in
Implementation steps:
-
First, we will sort the input array using an inbuilt function
Arrays.sort(nums) . -
Then, we will create a new function
kSumRecursive which takes following arguments :-
k - which tells how many numbers to be considered to get thetarget . -
target - the target value that we are trying to find. -
start - the starting index ofnums array, where to start from. -
nums - input array. -
path - list of integers, that we are adding as we call the function recursively, which number is added out ofk integers. -
result - list of quadruplets that we need to return as answer.
-
-
Next, let's write the base case for the recursive function, which is when
k == 2 , using awhile loop andleft andright bounds of array, find pairs of numbers that adds upto thetarget while ignoring the duplicates, and add each pair of numbers to theresult . -
Call the
kSumRecursive function recursively, by reducingk by1 each time, reduce the target by current numbertarget = target - nums[i] , and incrementstart index by 1, to start looking next set ofk-1 numbers from this index.
Complexity Analysis:
Time complexity: Above code runs in O(n k-1) time, in this case it is O(n3) where
Space complexity: O(k), for the temporary arrays we are using in recursion, also for the stack.
Above implementations source code can be found at