![]() |
VOOZH | about |
Given an array arr[] of integers and an integer target, the task is to find any quadruplet in arr[] such that it's sum is equal to the target.
Note: If there are multiple quadruplets with sum = target, return any one of them.
Examples:
Input: arr[] = [2, 4, 6, 8, 1, 3], target = 15
Output: [2, 4, 6, 3]
Explanation: The quadruplet {2, 4, 6, 3} has sum = 15.Input: arr[] = [1, 2, 3, 4, 10], target = 20
Output: []
Explanation: No quadruplet adds up to a sum of 20.
Table of Content
The idea is to generate all possible quadruplets using four nested loops and calculate the sum of each quadruplet. If the sum of a quadruplet is equal to target, return that quadruplet.
2 4 6 3
Initially, we sort the input array so that we can apply two pointers technique. Then, we fix the first two elements of the quadruplet using two nested loops and inside the second nested loop we use two pointers technique to find the remaining two elements. Set one pointer at the beginning (left) and another at the end (right) of the remaining array. We then check the sum of all these four elements and compare it with the given target:
- If sum < target, move left pointer towards right to increase the sum.
- If sum > target, move right pointer towards left to decrease the sum.
- If sum == target, we’ve found the quadruple.
1 2 4 8