4 Sum - Find any quadruplet having given sum
Last Updated :
23 Jul, 2025
Given an array arr[] of n 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(n^4) 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.
C++
// C++ program to find a quadruplet with sum
// equal to target by exploring all quadruplets
#include <iostream>
#include <vector>
using namespace std;
vector<int> findQuadruplet(vector<int>& arr, int target) {
int n = arr.size();
// Generating all possible quadruplets
for (int i = 0; i < n - 3; i++) {
for (int j = i + 1; j < n - 2; j++) {
for (int k = j + 1; k < n - 1; k++) {
for(int l = k + 1; l < n; l++) {
int currSum = arr[i] + arr[j] + arr[k] + arr[l];
// If current sum equals target, we have found desired quadruplet
if (currSum == target) {
return {arr[i], arr[j], arr[k], arr[l]};
}
}
}
}
}
// Return empty vector if no quadruplet found
return {};
}
int main() {
vector<int> arr = {2, 4, 6, 8, 1, 3};
int target = 15;
vector<int> res = findQuadruplet(arr, target);
for (int i = 0; i < res.size(); i++)
cout << res[i] << " ";
return 0;
}
C
// C program to find a quadruplet with sum
// equal to target by exploring all quadruplets
#include <stdio.h>
int* findQuadruplet(int* arr, int n, int target) {
// Generating all possible quadruplets
for (int i = 0; i < n - 3; i++) {
for (int j = i + 1; j < n - 2; j++) {
for (int k = j + 1; k < n - 1; k++) {
for (int l = k + 1; l < n; l++) {
int currSum = arr[i] + arr[j] + arr[k] + arr[l];
// If current sum equals target, we have found desired quadruplet
if (currSum == target) {
int* res = (int*)malloc(4 * sizeof(int));
res[0] = arr[i];
res[1] = arr[j];
res[2] = arr[k];
res[3] = arr[l];
return res;
}
}
}
}
}
// Return NULL if no quadruplet found
return NULL;
}
int main() {
int arr[] = {2, 4, 6, 8, 1, 3};
int target = 15;
int n = sizeof(arr) / sizeof(arr[0]);
int* res = findQuadruplet(arr, n, target);
if (res != NULL) {
for (int i = 0; i < 4; i++)
printf("%d ", res[i]);
}
return 0;
}
Java
// Java program to find a quadruple with sum
// equal to target by exploring all quadruplets
import java.util.ArrayList;
import java.util.List;
class GfG {
static List<Integer> findQuadruplet(int[] arr, int target) {
int n = arr.length;
// Generating all possible quadruplets
for (int i = 0; i < n - 3; i++) {
for (int j = i + 1; j < n - 2; j++) {
for (int k = j + 1; k < n - 1; k++) {
for (int l = k + 1; l < n; l++) {
int currSum = arr[i] + arr[j] + arr[k] + arr[l];
// If current sum equals target, we have found desired quadruplet
if (currSum == target) {
List<Integer> result = new ArrayList<>();
result.add(arr[i]);
result.add(arr[j]);
result.add(arr[k]);
result.add(arr[l]);
return result;
}
}
}
}
}
// Return empty list if no quadruplet found
return new ArrayList<>();
}
public static void main(String[] args) {
int[] arr = {2, 4, 6, 8, 1, 3};
int target = 15;
List<Integer> res = findQuadruplet(arr, target);
for (int i = 0; i < res.size(); i++) {
System.out.print(res.get(i) + " ");
}
}
}
Python
# Python program to find a quadruple with sum
# equal to target by exploring all quadruplets
def findQuadruplet(arr, target):
n = len(arr)
# Generating all possible quadruplets
for i in range(n - 3):
for j in range(i + 1, n - 2):
for k in range(j + 1, n - 1):
for l in range(k + 1, n):
currSum = arr[i] + arr[j] + arr[k] + arr[l]
# If current sum equals target, we have found desired quadruplet
if currSum == target:
return [arr[i], arr[j], arr[k], arr[l]]
# Return empty list if no quadruplet found
return []
if __name__ == "__main__":
arr = [2, 4, 6, 8, 1, 3]
target = 15
res = findQuadruplet(arr, target)
for i in range(len(res)):
print(res[i], end=" ")
C#
// C# program to find a quadruple with sum
// equal to target by exploring all quadruplets
using System;
using System.Collections.Generic;
class GfG {
static List<int> findQuadruplet(List<int> arr, int target) {
int n = arr.Count;
// Generating all possible quadruplets
for (int i = 0; i < n - 3; i++) {
for (int j = i + 1; j < n - 2; j++) {
for (int k = j + 1; k < n - 1; k++) {
for(int l = k + 1; l < n; l++) {
int currSum = arr[i] + arr[j] + arr[k] + arr[l];
// If current sum equals target, we have found desired quadruplet
if (currSum == target) {
return new List<int> { arr[i], arr[j], arr[k], arr[l] };
}
}
}
}
}
// Return empty list if no quadruplet found
return new List<int>();
}
static void Main() {
List<int> arr = new List<int> { 2, 4, 6, 8, 1, 3 };
int target = 15;
List<int> res = findQuadruplet(arr, target);
for (int i = 0; i < res.Count; i++)
Console.Write(res[i] + " ");
}
}
JavaScript
// JavaScript program to find a quadruplet with sum
// equal to target by exploring all quadruplets
function findQuadruplet(arr, target) {
const n = arr.length;
// Generating all possible quadruplets
for (let i = 0; i < n - 3; i++) {
for (let j = i + 1; j < n - 2; j++) {
for (let k = j + 1; k < n - 1; k++) {
for (let l = k + 1; l < n; l++) {
const currSum = arr[i] + arr[j] + arr[k] + arr[l];
// If current sum equals target, we have found desired quadruplet
if (currSum === target) {
return [arr[i], arr[j], arr[k], arr[l]];
}
}
}
}
}
// Return empty array if no quadruplet found
return [];
}
const arr = [2, 4, 6, 8, 1, 3];
const target = 15;
const res = findQuadruplet(arr, target);
console.log(res.join(" "));
[Expected Approach] Sorting and Two Pointers Technique – O(n^3) 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.
C++
// C++ program to find a quadruplet having
// sum target using two pointers technique
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> findQuadruplet(vector<int> &arr, int target) {
int n = arr.size();
// Sorting the array to use two pointers technique
sort(arr.begin(), arr.end());
for (int i = 0; i < n - 3; i++) {
for (int j = i + 1; j < n - 2; j++) {
int l = j + 1, r = n - 1;
while (l < r) {
int currSum = arr[i] + arr[j] + arr[l] + arr[r];
// If currSum is equal to target,
// we have found the desired quadruplet
if (currSum == target) {
return {arr[i], arr[j], arr[l], arr[r]};
}
// If currSum exceeds the target, move
// the right pointer left to reduce the sum
if (currSum > target)
r--;
// If currSum is less than target, move
// the left pointer right to increase the sum
else
l++;
}
}
}
// Return empty array if no quadruplet found
return {};
}
int main() {
vector<int> arr = {2, 4, 6, 8, 1, 3};
int target = 15;
vector<int> res = findQuadruplet(arr, target);
for (int i = 0; i < res.size(); i++)
cout << res[i] << " ";
return 0;
}
C
// C program to find a quadruplet having
// sum target using two pointer technique
#include <stdio.h>
int compare(const void* a, const void* b) {
return (*(int*)a - *(int*)b);
}
int* findQuadruplet(int* arr, int n, int target) {
// Sorting the array to use two pointers technique
qsort(arr, n, sizeof(int), compare);
for (int i = 0; i < n - 3; i++) {
for (int j = i + 1; j < n - 2; j++) {
int l = j + 1, r = n - 1;
while (l < r) {
int currSum = arr[i] + arr[j] + arr[l] + arr[r];
// If currSum is equal to target,
// we have found the desired quadruplet
if (currSum == target) {
int* result = (int*)malloc(4 * sizeof(int));
result[0] = arr[i];
result[1] = arr[j];
result[2] = arr[l];
result[3] = arr[r];
return result;
}
// If currSum exceeds the target, move
// the right pointer left to reduce the sum
if (currSum > target)
r--;
// If currSum is less than target, move
// the left pointer right to increase the sum
else
l++;
}
}
}
// Return NULL if no quadruplet found
return NULL;
}
int main() {
int arr[] = {2, 4, 6, 8, 1, 3};
int target = 15;
int n = sizeof(arr) / sizeof(arr[0]);
int* res = findQuadruplet(arr, n, target);
if (res != NULL) {
for (int i = 0; i < 4; i++)
printf("%d ", res[i]);
}
return 0;
}
Java
// Java program to find a quadruplet having
// sum target using two pointer technique
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
class GfG {
static List<Integer> findQuadruplet(int[] arr, int target) {
int n = arr.length;
// Sorting the array to use two pointers technique
Arrays.sort(arr);
for (int i = 0; i < n - 3; i++) {
for (int j = i + 1; j < n - 2; j++) {
int l = j + 1, r = n - 1;
while (l < r) {
int currSum = arr[i] + arr[j] + arr[l] + arr[r];
// If currSum is equal to target,
// we have found the desired quadruplet
if (currSum == target)
return Arrays.asList(arr[i], arr[j], arr[l], arr[r]);
// If currSum exceeds the target, move
// the right pointer left to reduce the sum
if (currSum > target)
r--;
// If currSum is less than target, move
// the left pointer right to increase the sum
else
l++;
}
}
}
// Return empty array if no quadruplet found
return new ArrayList<>();
}
public static void main(String[] args) {
int[] arr = {2, 4, 6, 8, 1, 3};
int target = 15;
List<Integer> res = findQuadruplet(arr, target);
for (int i = 0; i < res.size(); i++)
System.out.print(res.get(i) + " ");
}
}
Python
# Python program to find a quadruplet having
# sum target using two pointers technique
def findQuadruplet(arr, target):
n = len(arr)
# Sorting the array to use two pointers technique
arr.sort()
for i in range(n - 3):
for j in range(i + 1, n - 2):
l, r = j + 1, n - 1
while l < r:
currSum = arr[i] + arr[j] + arr[l] + arr[r]
# If currSum is equal to target,
# we have found the desired quadruplet
if currSum == target:
return [arr[i], arr[j], arr[l], arr[r]]
# If currSum exceeds the target, move
# the right pointer left to reduce the sum
if currSum > target:
r -= 1
# If currSum is less than target, move
# the left pointer right to increase the sum
else:
l += 1
# Return empty array if no quadruplet found
return []
if __name__ == "__main__":
arr = [2, 4, 6, 8, 1, 3]
target = 15
res = findQuadruplet(arr, target)
for i in range(len(res)):
print(res[i], end=" ")
C#
// C# program to find a quadruplet having
// sum target using two pointer technique
using System;
using System.Collections.Generic;
class GfG {
static List<int> findQuadruplet(List<int> arr, int target) {
int n = arr.Count;
// Sorting the array to use two pointers technique
arr.Sort();
for (int i = 0; i < n - 3; i++) {
for (int j = i + 1; j < n - 2; j++) {
int l = j + 1, r = n - 1;
while (l < r) {
int currSum = arr[i] + arr[j] + arr[l] + arr[r];
// If currSum is equal to target,
// we have found the desired quadruplet
if (currSum == target) {
return new List<int> { arr[i], arr[j], arr[l], arr[r] };
}
// If currSum exceeds the target, move
// the right pointer left to reduce the sum
if (currSum > target)
r--;
// If currSum is less than target, move
// the left pointer right to increase the sum
else
l++;
}
}
}
// Return empty array if no quadruplet found
return new List<int>();
}
static void Main() {
List<int> arr = new List<int> { 2, 4, 6, 8, 1, 3 };
int target = 15;
List<int> res = findQuadruplet(arr, target);
for (int i = 0; i < res.Count; i++)
Console.Write(res[i] + " ");
}
}
JavaScript
// JavaScript program to find a quadruplet having
// sum target using two pointer technique
function findQuadruplet(arr, target) {
let n = arr.length;
// Sorting the array to use two pointers technique
arr.sort((a, b) => a - b);
for (let i = 0; i < n - 3; i++) {
for (let j = i + 1; j < n - 2; j++) {
let l = j + 1, r = n - 1;
while (l < r) {
let currSum = arr[i] + arr[j] + arr[l] + arr[r];
// If currSum is equal to target,
// we have found the desired quadruplet
if (currSum === target) {
return [arr[i], arr[j], arr[l], arr[r]];
}
// If currSum exceeds the target, move
// the right pointer left to reduce the sum
if (currSum > target) {
r--;
}
// If currSum is less than target, move
// the left pointer right to increase the sum
else {
l++;
}
}
}
}
// Return empty array if no quadruplet found
return [];
}
const arr = [2, 4, 6, 8, 1, 3];
const target = 15;
const res = findQuadruplet(arr, target);
console.log(res.join(" "));
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem