![]() |
VOOZH | about |
Given an array of integers, check if there are four elements in the array with given sum.
Example:
Input: arr = {10, 20, 30, 40, 1, 2}, target = 91
Output: True
Explanation: Sum of 20 + 30 + 40 + 1 = 91Input: arr = {1, 2, 3, 4, 5, 9, 7, 8}, target = 16
Output: True
Explanation: Sum of output is equal to 16, i.e. 1 + 3 + 5 + 7 = 16.Input: arr = {1, 1, 2, 2], target = 4
Output: False
Explanation: There is no Quadruple with given target
Generate all possible quadruples and compare the sum of every quadruple with target. The following code implements this simple method using four nested loops.
True
Initially, we sort the input array so that we can apply two pointer technique.. Then, run two nested nested loops for the first and second element in the array. Inside the second nested loop, we simply use 2 Sum solution to find the remaining two elements.
If the sum of four elements is less than the required sum, then move the left pointer to increase the sum, otherwise if the sum of four elements is more than the required sum, then move the right pointer to decrease the sum.
True
We pick first two elements using two nested loops. For the remaining 2 elements, we simply use hashing based 2 sum solution inside the two loops.
True