VOOZH about

URL: https://www.geeksforgeeks.org/dsa/4-sum-find-any-quadruplet-having-given-sum/

⇱ 4 Sum - Find any quadruplet having given sum - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

4 Sum - Find any quadruplet having given sum

Last Updated : 3 Feb, 2026

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.

[Naive Approach] - Explore all the subsets of size four - O(n4) Time and O(1) Space

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.


Output
2 4 6 3 

[Expected Approach] Sorting and Two Pointers Technique – O(n3) time and O(1) space

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.

Output
1 2 4 8 
Comment
Article Tags: