VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-four-numbers-with-sum-equal-to-given-sum/

⇱ 4 Sum - Check if a Quadruple with given Sum Exists in an Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

4 Sum - Check if a Quadruple with given Sum Exists in an Array

Last Updated : 14 Nov, 2025

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 = 91

Input: 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

[Naive Solution] Using Four Nested Loop - O(n^4) Time and O(1) Space:

Generate all possible quadruples and compare the sum of every quadruple with target. The following code implements this simple method using four nested loops.


Output
True

[Expected Approach 1] Sorting and Two Pointer Technique - O(n^3) Time and O(1) Space:

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.


Output
True

[Expected Approach 2] Hash Map - O(n^2) Time and O(n^2) Space:

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.


Output
True


Comment