![]() |
VOOZH | about |
Given an array arr[] and a target value, the task is to find the count of quadruplets present in the given array having sum equal to the given target.
Examples:
Input: arr[] = [1, 5, 3, 1, 2, 10], target = 20
Output: 1
Explanation: Only quadruplet satisfying the conditions is arr[1] + arr[2] + arr[4] + arr[5] = 5 + 3 + 2 + 10 = 20.Input: arr[] = [1, 1, 1, 1, 1], target = 4
Output: 5
Explanation:
arr[0] + arr[1] + arr[2] + arr[3] = 4
arr[0] + arr[1] + arr[3] + arr[4] = 4
arr[0] + arr[1] + arr[2] + arr[4] = 4
arr[0] + arr[2] + arr[3] + arr[4] = 4
arr[1] + arr[2] + arr[3] + arr[4] = 4Input: arr = [4, 3, -13, 3], target = -3
Output: 1
Explanation: There is only 1 quadruplet with sum = -3, that is [4, 3, -13, 3].
Table of Content
The idea is to generate all possible combinations of length 4 from the given array. For each quadruplet, if the sum equals target, then increment the counter by 1.
5
Time Complexity: O(n4), where n is the size of the given array.
Auxiliary Space: O(1)
The idea is to use Hash Map or Dictionary. For every pair (arr[i], arr[j]) where j > i, we simply use the logic of counting pairs for the subarray from (j + 1) to end of the array for target equals to given target - arr[i] - arr[j].
5
Time complexity: O(n3), where n is the size of the given array.
Auxiliary Space: O(n)
The idea is similar to the above approach using hashing. In this approach, we fix the 3rd element, then find and store the frequency of sums of all possible first two elements of any quadruplet of the given array. Follow the below steps to solve the problem:
5
Time Complexity: O(n2), where n is the size of the given array.
Auxiliary Space: O(n2), as we are storing sum of all possible pairs in the hash map.