Open In App

Find four elements that sum to a given value (4Sum) | Set 2

Last Updated : 16 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array of integers, find anyone combination of four elements in the array whose sum is equal to a given value X.

Example:

Input: array = {10, 2, 3, 4, 5, 9, 7, 8}, X = 23
Output: 3 5 7 8
Explanation: Sum of output is equal to 23, i.e. 3 + 5 + 7 + 8 = 23.

Input: array = {1, 2, 3, 4, 5, 9, 7, 8}, X = 16
Output: 1 3 5 7
Explanation: Sum of output is equal to 16, i.e. 1 + 3 + 5 + 7 = 16.

We have discussed an O(n3) algorithm in the previous post on this topic. The problem can be solved in O(n2 Logn) time with the help of auxiliary space. 

4Sum using Two Pointers Algorithm. 

Below is the implementation of the above approach: 

C++
// C++ program to find 4 elements
// with given sum
#include <bits/stdc++.h>
using namespace std;

// The following structure is needed
// to store pair sums in aux[]
class pairSum {
public:
    // index (int A[]) of first element in pair
    int first;

    // index of second element in pair
    int sec;

    // sum of the pair
    int sum;
};

// Following function is needed
// for library function qsort()
int compare(const void* a, const void* b)
{
    return ((*(pairSum*)a).sum - (*(pairSum*)b).sum);
}

// Function to check if two given pairs
// have any common element or not
bool noCommon(pairSum a, pairSum b)
{
    if (a.first == b.first || a.first == b.sec
        || a.sec == b.first || a.sec == b.sec)
        return false;
    return true;
}

// The function finds four
// elements with given sum X
void findFourElements(int arr[], int n, int X)
{
    int i, j;

    // Create an auxiliary array
    // to store all pair sums
    int size = (n * (n - 1)) / 2;
    pairSum aux[size];

    // Generate all possible pairs
    // from A[] and store sums
    // of all possible pairs in aux[]
    int k = 0;
    for (i = 0; i < n - 1; i++) {
        for (j = i + 1; j < n; j++) {
            aux[k].sum = arr[i] + arr[j];
            aux[k].first = i;
            aux[k].sec = j;
            k++;
        }
    }

    // Sort the aux[] array using
    // library function for sorting
    qsort(aux, size, sizeof(aux[0]), compare);

    // Now start two index variables
    // from two corners of array
    // and move them toward each other.
    i = 0;
    j = size - 1;
    while (i < size && j >= 0) {
        if ((aux[i].sum + aux[j].sum == X)
            && noCommon(aux[i], aux[j])) {
            cout << arr[aux[i].first] << ", "
                 << arr[aux[i].sec] << ", "
                 << arr[aux[j].first] << ", "
                 << arr[aux[j].sec] << endl;
            return;
        }
        else if (aux[i].sum + aux[j].sum < X)
            i++;
        else
            j--;
    }
}

// Driver code
int main()
{
    int arr[] = { 10, 20, 30, 40, 1, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int X = 91;
  
    // Function Call
    findFourElements(arr, n, X);
    return 0;
}

// This is code is contributed by rathbhupendra
C
// C program to find 4 elements
// with given sum
#include <stdio.h>
#include <stdlib.h>

// The following structure is
// needed to store pair sums in aux[]
struct pairSum {

    // index (int A[]) of first element in pair
    int first;

    // index of second element in pair
    int sec;

    // sum of the pair
    int sum;
};

// Following function is needed
// for library function qsort()
int compare(const void* a, const void* b)
{
    return ((*(pairSum*)a).sum - (*(pairSum*)b).sum);
}

// Function to check if two given
// pairs have any common element or not
bool noCommon(struct pairSum a, struct pairSum b)
{
    if (a.first == b.first || a.first == b.sec
        || a.sec == b.first || a.sec == b.sec)
        return false;
    return true;
}

// The function finds four
// elements with given sum X
void findFourElements(int arr[], int n, int X)
{
    int i, j;

    // Create an auxiliary array
    // to store all pair sums
    int size = (n * (n - 1)) / 2;
    struct pairSum aux[size];

    // Generate all possible pairs
    // from A[] and store sums
    // of all possible pairs in aux[]
    int k = 0;
    for (i = 0; i < n - 1; i++) {
        for (j = i + 1; j < n; j++) {
            aux[k].sum = arr[i] + arr[j];
            aux[k].first = i;
            aux[k].sec = j;
            k++;
        }
    }

    // Sort the aux[] array using
    // library function for sorting
    qsort(aux, size, sizeof(aux[0]), compare);

    // Now start two index variables
    // from two corners of array
    // and move them toward each other.
    i = 0;
    j = size - 1;
    while (i < size && j >= 0) {
        if ((aux[i].sum + aux[j].sum == X)
            && noCommon(aux[i], aux[j])) {
            printf("%d, %d, %d, %d\n", arr[aux[i].first],
                   arr[aux[i].sec], arr[aux[j].first],
                   arr[aux[j].sec]);
            return;
        }
        else if (aux[i].sum + aux[j].sum < X)
            i++;
        else
            j--;
    }
}

// Driver code
int main()
{
    int arr[] = { 10, 20, 30, 40, 1, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int X = 91;
   
    // Function call
    findFourElements(arr, n, X);
    return 0;
}
Java
// Java program to find 4 elements
// with given sum
import java.util.*;
class GFG {

  // The following structure is needed
  // to store pair sums in aux[]
  static class pairSum {

    // Index (int A[]) of first element in pair
    public int first;

    // Index of second element in pair
    public int sec;

    // Sum of the pair
    public int sum;
  }

  // Function to check if two given pairs
  // have any common element or not
  static boolean noCommon(pairSum a, pairSum b)
  {
    if (a.first == b.first || a.first == b.sec
        || a.sec == b.first || a.sec == b.sec)
      return false;

    return true;
  }

  // The function finds four
  // elements with given sum X
  static void findFourElements(int[] myArr, int sum)
  {
    int i, j;
    int length = myArr.length;

    // Create an auxiliary array to
    // store all pair sums
    int size = (length * (length - 1)) / 2;
    pairSum[] aux = new pairSum[size];

    // Generate all possible pairs
    // from A[] and store sums
    // of all possible pairs in aux[]
    int k = 0;
    for (i = 0; i < length - 1; i++) {
      for (j = i + 1; j < length; j++) {
        aux[k] = new pairSum();
        aux[k].sum = myArr[i] + myArr[j];
        aux[k].first = i;
        aux[k].sec = j;
        k++;
      }
    }

    // Sort the aux[] array using
    // library function for sorting
    Arrays.sort(aux, new Comparator<pairSum>() {
      // Following function is needed for sorting
      // pairSum array
      public int compare(pairSum a, pairSum b)
      {
        return (a.sum - b.sum);
      }
    });

    // Now start two index variables
    // from two corners of array
    // and move them toward each other.
    i = 0;
    j = size - 1;
    while (i < size && j >= 0) {
      if ((aux[i].sum + aux[j].sum == sum)
          && noCommon(aux[i], aux[j])) {
        String output = myArr[aux[i].first] + ", "
          + myArr[aux[i].sec] + ", "
          + myArr[aux[j].first] + ", "
          + myArr[aux[j].sec];
        System.out.println(output);
        return;
      }
      else if (aux[i].sum + aux[j].sum < sum)
        i++;
      else
        j--;
    }
  }

  public static void main(String[] args)
  {
    int[] arr = { 10, 20, 30, 40, 1, 2 };
    int X = 91;

    // Function call
    findFourElements(arr, X);
  }
}

// This code is contributed by phasing17
Python3
# Python3 program to find 4 elements
# with given sum

# The following structure is needed
# to store pair sums in aux[]


class pairSum:

    def __init__(self):
        # Index (int A[]) of first element in pair
        self.first = ""

        # Index of second element in pair
        self.sec = ""

        # Sum of the pair
        self.sum = ""


# Function to check if two given pairs
# have any common element or not
def noCommon(a, b):
    if (a.first == b.first or a.first == b.sec or a.sec == b.first or a.sec == b.sec):
        return False

    return True


# The function finds four
# elements with given sum X
def findFourElements(myArr, sum):

    length = len(myArr)

    # Create an auxiliary array to
    # store all pair sums
    size = ((length * (length - 1)) // 2)
    aux = [None for _ in range(size)]

    # Generate all possible pairs
    # from A[] and store sums
    # of all possible pairs in aux[]
    k = 0
    for i in range(length - 1):
        for j in range(i + 1, length):
            aux[k] = pairSum()
            aux[k].sum = myArr[i] + myArr[j]
            aux[k].first = i
            aux[k].sec = j
            k += 1

    # Sort the aux[] array using
    # library function for sorting
    aux.sort(key=lambda x: x.sum)

    # Now start two index variables
    # from two corners of array
    # and move them toward each other.
    i = 0
    j = size - 1
    while (i < size and j >= 0):
        if ((aux[i].sum + aux[j].sum == sum)
                and noCommon(aux[i], aux[j])):
            print(myArr[aux[i].first], myArr[aux[i].sec],
                  myArr[aux[j].first], myArr[aux[j].sec], sep=", ")
            return

        elif (aux[i].sum + aux[j].sum < sum):
            i += 1
        else:
            j -= 1


# Driver Code
arr = [10, 20, 30, 40, 1, 2]
X = 91

# Function call
findFourElements(arr, X)


# This code is contributed by phasing17
C#
// C# program to find 4 elements
// with given sum
using System;

class GFG{

// The following structure is needed
// to store pair sums in aux[]
class pairSum
{
    
    // Index (int A[]) of first element in pair
    public int first;

    // Index of second element in pair
    public int sec;

    // Sum of the pair
    public int sum;
}

// Function to check if two given pairs
// have any common element or not
static bool noCommon(pairSum a, pairSum b)
{
    if (a.first == b.first || a.first == b.sec || 
        a.sec == b.first || a.sec == b.sec)
        return false;
        
    return true;
}

// Following function is needed for sorting
// pairSum array
static int compare(pairSum a, pairSum b)
{
    return (a.sum - b.sum);
}

// The function finds four
// elements with given sum X
static void findFourElements(int[] myArr, int sum)
{
    int i, j;
    int length = myArr.Length;

    // Create an auxiliary array to 
    // store all pair sums
    int size = (length * (length - 1)) / 2;
    pairSum[] aux = new pairSum[size];

    // Generate all possible pairs
    // from A[] and store sums
    // of all possible pairs in aux[]
    int k = 0;
    for(i = 0; i < length - 1; i++)
    {
        for(j = i + 1; j < length; j++)
        {
            aux[k] = new pairSum();
            aux[k].sum = myArr[i] + myArr[j];
            aux[k].first = i;
            aux[k].sec = j;
            k++;
        }
    }

    // Sort the aux[] array using
    // library function for sorting
    Array.Sort(aux, compare);

    // Now start two index variables
    // from two corners of array
    // and move them toward each other.
    i = 0;
    j = size - 1;
    while (i < size && j >= 0)
    {
        if ((aux[i].sum + aux[j].sum == sum) && 
            noCommon(aux[i], aux[j]))
        {
            string output = myArr[aux[i].first] + ", " +
                            myArr[aux[i].sec] + ", " + 
                            myArr[aux[j].first] + ", " + 
                            myArr[aux[j].sec];
            Console.WriteLine(output);
            return;
        }
        else if (aux[i].sum + aux[j].sum < sum)
            i++;
        else
            j--;
    }
}

// Driver code
static public void Main()
{
    int[] arr = { 10, 20, 30, 40, 1, 2 };
    int X = 91;

    // Function call
    findFourElements(arr, X);
}
}

// This code is contributed by srastog
Javascript
// JavaScript program to find 4 elements
// with given sum

// The following structure is needed
// to store pair sums in aux[]
let pairSum = {

    // Index (int A[]) of first element in pair
    first : "",

    // Index of second element in pair
    sec : "",

    // Sum of the pair
    sum : ""
};

// Function to check if two given pairs
// have any common element or not
function noCommon(a, b)
{
    if (a.first == b.first || a.first == b.sec
        || a.sec == b.first || a.sec == b.sec)
        return false;

    return true;
}

// The function finds four
// elements with given sum X
function findFourElements(myArr, sum)
{
    let i, j;
    let length = myArr.length;

    // Create an auxiliary array to
    // store all pair sums
    let size = Math.floor((length * (length - 1)) / 2);
    let aux = new Array(size);

    // Generate all possible pairs
    // from A[] and store sums
    // of all possible pairs in aux[]
    let k = 0;
    for (i = 0; i < length - 1; i++) {
        for (j = i + 1; j < length; j++) {
            aux[k] = new Object();
            aux[k].sum = myArr[i] + myArr[j];
            aux[k].first = i;
            aux[k].sec = j;
            k++;
        }
    }

    // Sort the aux[] array using
    // library function for sorting
    aux.sort(
        // Following function is needed for sorting
        // pairSum array
        function(x, y) { return x.sum - y.sum; });

    // Now start two index variables
    // from two corners of array
    // and move them toward each other.
    i = 0;
    j = size - 1;
    while (i < size && j >= 0) {
        if ((aux[i].sum + aux[j].sum == sum)
            && noCommon(aux[i], aux[j])) {
            let output = myArr[aux[i].first] + ", "
                         + myArr[aux[i].sec] + ", "
                         + myArr[aux[j].first] + ", "
                         + myArr[aux[j].sec];
            console.log(output);
            return;
        }
        else if (aux[i].sum + aux[j].sum < sum)
            i++;
        else
            j--;
    }
}

let arr = [ 10, 20, 30, 40, 1, 2 ];
let X = 91;

// Function call
findFourElements(arr, X);

// This code is contributed by phasing17

Output
20, 1, 30, 40

Please note that the above code prints only one quadruple. If we remove the return statement and add statements “i++; j–;”, then it prints same quadruple five times. The code can modified to print all quadruples only once. It has been kept this way to keep it simple. 
Complexity Analysis: 

  • Time complexity: O(n^2Logn). 
    The step 1 takes O(n^2) time. The second step is sorting an array of size O(n^2). Sorting can be done in O(n^2Logn) time using merge sort or heap sort or any other O(nLogn) algorithm. The third step takes O(n^2) time. So overall complexity is O(n^2Logn).
  • Auxiliary Space: O(n^2). 
    The size of the auxiliary array is O(n^2). The big size of the auxiliary array can be a concern in this method.

4Sum using Hashing:

  • Store sums of all pairs in a hash table
  • Traverse through all pairs again and search for X – (current pair sum) in the hash table.
  • If a pair is found with the required sum, then make sure that all elements are distinct array elements and an element is not considered more than once.

Below image is a dry run of the above approach: 

Below is the implementation of the above approach: 

C++
// A hashing based  CPP program
// to find if there are
// four elements with given sum.
#include <bits/stdc++.h>
using namespace std;

// The function finds four
// elements with given sum X
void findFourElements(int arr[], int n, int X)
{
    // Store sums of all pairs
    // in a hash table
    unordered_map<int, pair<int, int> > mp;
    for (int i = 0; i < n - 1; i++)
        for (int j = i + 1; j < n; j++)
            mp[arr[i] + arr[j]] = { i, j };

    // Traverse through all pairs and search
    // for X - (current pair sum).
    for (int i = 0; i < n - 1; i++) {
        for (int j = i + 1; j < n; j++) {
            int sum = arr[i] + arr[j];

            // If X - sum is present in hash table,
            if (mp.find(X - sum) != mp.end()) {

                // Making sure that all elements are
                // distinct array elements and an element
                // is not considered more than once.
                pair<int, int> p = mp[X - sum];
                if (p.first != i && p.first != j
                    && p.second != i && p.second != j) {
                    cout << arr[i] << ", " << arr[j] << ", "
                         << arr[p.first] << ", "
                         << arr[p.second];
                    return;
                }
            }
        }
    }
}

// Driver code
int main()
{
    int arr[] = { 10, 20, 30, 40, 1, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int X = 91;
   
    // Function call
    findFourElements(arr, n, X);
    return 0;
}
Java
// A hashing based Java program to find
// if there are four elements with given sum.
import java.util.HashMap;
class GFG {
    static class pair {
        int first, second;
        public pair(int first, int second)
        {
            this.first = first;
            this.second = second;
        }
    }

    // The function finds four elements
    // with given sum X
    static void findFourElements(int arr[], int n, int X)
    {
        // Store sums of all pairs in a hash table
        HashMap<Integer, pair> mp
            = new HashMap<Integer, pair>();
        for (int i = 0; i < n - 1; i++)
            for (int j = i + 1; j < n; j++)
                mp.put(arr[i] + arr[j], new pair(i, j));

        // Traverse through all pairs and search
        // for X - (current pair sum).
        for (int i = 0; i < n - 1; i++) {
            for (int j = i + 1; j < n; j++) {
                int sum = arr[i] + arr[j];

                // If X - sum is present in hash table,
                if (mp.containsKey(X - sum)) {

                    // Making sure that all elements are
                    // distinct array elements and an
                    // element is not considered more than
                    // once.
                    pair p = mp.get(X - sum);
                    if (p.first != i && p.first != j
                        && p.second != i && p.second != j) {
                        System.out.print(
                            arr[i] + ", " + arr[j] + ", "
                            + arr[p.first] + ", "
                            + arr[p.second]);
                        return;
                    }
                }
            }
        }
    }

    // Driver Code
    public static void main(String[] args)
    {
        int arr[] = { 10, 20, 30, 40, 1, 2 };
        int n = arr.length;
        int X = 91;
      
        // Function call
        findFourElements(arr, n, X);
    }
}

// This code is contributed by Princi Singh
Python3
# A hashing based Python program to find if there are
# four elements with given summ.

# The function finds four elements with given summ X


def findFourElements(arr, n, X):

    # Store summs of all pairs in a hash table
    mp = {}
    for i in range(n - 1):
        for j in range(i + 1, n):
            mp[arr[i] + arr[j]] = [i, j]

    # Traverse through all pairs and search
    # for X - (current pair summ).
    for i in range(n - 1):
        for j in range(i + 1, n):
            summ = arr[i] + arr[j]

            # If X - summ is present in hash table,
            if (X - summ) in mp:

                # Making sure that all elements are
                # distinct array elements and an element
                # is not considered more than once.
                p = mp[X - summ]
                if (p[0] != i and p[0] != j and p[1] != i and p[1] != j):
                    print(arr[i], ", ", arr[j], ", ",
                          arr[p[0]], ", ", arr[p[1]], sep="")
                    return


# Driver code
arr = [10, 20, 30, 40, 1, 2]
n = len(arr)
X = 91

# Function call
findFourElements(arr, n, X)

# This is code is contributed by shubhamsingh10
C#
// A hashing based C# program to find
// if there are four elements with given sum.
using System;
using System.Collections.Generic;

class GFG {
    public class pair {
        public int first, second;
        public pair(int first, int second)
        {
            this.first = first;
            this.second = second;
        }
    }

    // The function finds four elements
    // with given sum X
    static void findFourElements(int[] arr, int n, int X)
    {
        // Store sums of all pairs in a hash table
        Dictionary<int, pair> mp
            = new Dictionary<int, pair>();
        for (int i = 0; i < n - 1; i++)
            for (int j = i + 1; j < n; j++)
                if (mp.ContainsKey(arr[i] + arr[j]))
                    mp[arr[i] + arr[j]] = new pair(i, j);
                else
                    mp.Add(arr[i] + arr[j], new pair(i, j));

        // Traverse through all pairs and search
        // for X - (current pair sum).
        for (int i = 0; i < n - 1; i++) {
            for (int j = i + 1; j < n; j++) {
                int sum = arr[i] + arr[j];

                // If X - sum is present in hash table,
                if (mp.ContainsKey(X - sum)) {

                    // Making sure that all elements are
                    // distinct array elements and an
                    // element is not considered more than
                    // once.
                    pair p = mp[X - sum];
                    if (p.first != i && p.first != j
                        && p.second != i && p.second != j) {
                        Console.Write(arr[i] + ", " + arr[j]
                                      + ", " + arr[p.first]
                                      + ", "
                                      + arr[p.second]);
                        return;
                    }
                }
            }
        }
    }

    // Driver Code
    public static void Main(String[] args)
    {
        int[] arr = { 10, 20, 30, 40, 1, 2 };
        int n = arr.Length;
        int X = 91;
      
        // Function call
        findFourElements(arr, n, X);
    }
}

// This code is contributed by 29AjayKumar
Javascript
<script>
// A hashing based Javascript program to find
// if there are four elements with given sum.

// The function finds four elements
// with given sum X
function findFourElements(arr,n,X)
{
    // Store sums of all pairs in a hash table
        let mp = new Map();
        for (let i = 0; i < n - 1; i++)
            for (let j = i + 1; j < n; j++)
                mp.set(arr[i] + arr[j], [i, j]);
 
        // Traverse through all pairs and search
        // for X - (current pair sum).
        for (let i = 0; i < n - 1; i++) {
            for (let j = i + 1; j < n; j++) {
                let sum = arr[i] + arr[j];
 
                // If X - sum is present in hash table,
                if (mp.has(X - sum)) {
 
                    // Making sure that all elements are
                    // distinct array elements and an
                    // element is not considered more than
                    // once.
                    let p = mp.get(X - sum);
                    if (p[0] != i && p[0] != j
                        && p[1] != i && p[1] != j) {
                        document.write(
                            arr[i] + ", " + arr[j] + ", "
                            + arr[p[0]] + ", "
                            + arr[p[1]]);
                        return;
                    }
                }
            }
        }
}

// Driver Code
let arr=[ 10, 20, 30, 40, 1, 2];
let  n = arr.length;
let  X = 91;

// Function call
findFourElements(arr, n, X);

// This code is contributed by rag2127
</script>

Output
20, 30, 40, 1

Complexity Analysis: 

  • Time complexity: O(n^2). 
    Nested traversal is needed to store all pairs in the hash Map.
  • Auxiliary Space: O(n^2). 
    All n*(n-1) pairs are stored in hash Map so the space required is O(n^2)
    Please write comments if you find any of the above codes/algorithms incorrect, or find other ways to solve the same problem.

4Sum solution having no duplicate elements:

  • Store sums of all pairs in a hash table
  • Traverse through all pairs again and search for X – (current pair sum) in the hash table.
  • Consider a temp array that is initially stored with zeroes. It is changed to 1 when we get 4 elements that sum up to the required value.
  • If a pair is found with the required sum, then make sure that all elements are distinct array elements and check if the value in temp array is 0 so that duplicates are not considered.

Below is the implementation of the code: 

C++
// C++ program to find four  
// elements with the given sum 
#include <bits/stdc++.h>
using namespace std;

// Function to find 4 elements that add up to 
// given sum 
void fourSum(int X, int arr[], map<int, 
             pair<int, int>> Map, int N) 
{ 
    int temp[N]; 

    // Iterate from 0 to temp.length 
    for (int i = 0; i < N; i++) 
        temp[i] = 0; 

    // Iterate from 0 to arr.length 
    for (int i = 0; i < N - 1; i++) 
    { 

        // Iterate from i + 1 to arr.length 
        for (int j = i + 1; j < N; j++)
        { 

            // Store curr_sum = arr[i] + arr[j] 
            int curr_sum = arr[i] + arr[j]; 

            // Check if X - curr_sum if present 
            // in map 
            if (Map.find(X - curr_sum) != Map.end()) 
            { 

                // Store pair having map value 
                // X - curr_sum 
                pair<int, int> p = Map[X - curr_sum]; 

                if (p.first != i && p.second != i 
                    && p.first != j && p.second != j 
                    && temp[p.first] == 0
                    && temp[p.second] == 0 && temp[i] == 0
                    && temp[j] == 0)
                { 

                    // Print the output 
                    cout << arr[i] << "," << arr[j] <<
                      "," << arr[p.first] << "," << arr[p.second];
                    temp[p.second] = 1; 
                    temp[i] = 1; 
                    temp[j] = 1; 
                    break; 
                } 
            } 
        } 
    } 
} 

// Program for two Sum 
map<int, pair<int, int>> twoSum(int nums[], int N) 
{ 
    map<int, pair<int, int>> Map; 
    for (int i = 0; i < N - 1; i++)
    { 
        for (int j = i + 1; j < N; j++)
        { 
            Map[nums[i] + nums[j]].first = i;
            Map[nums[i] + nums[j]].second = j;
        } 
    } 
    return Map; 
} 

// Driver code
int main()
{
    int arr[] = { 10, 20, 30, 40, 1, 2 }; 
    int n = sizeof(arr) / sizeof(arr[0]); 
    int X = 91; 
    map<int, pair<int, int>> Map = twoSum(arr, n); 
    
    // Function call 
    fourSum(X, arr, Map, n); 

    return 0;
}

// This code is contributed by divyesh072019
Java
// Java program to find four 
// elements with the given sum
import java.util.*;

class fourElementWithSum {

    // Function to find 4 elements that add up to
    // given sum
    public static void fourSum(int X, int[] arr,
                               Map<Integer, pair> map)
    {
        int[] temp = new int[arr.length];

        // Iterate from 0 to temp.length
        for (int i = 0; i < temp.length; i++)
            temp[i] = 0;

        // Iterate from 0 to arr.length
        for (int i = 0; i < arr.length - 1; i++) {

            // Iterate from i + 1 to arr.length
            for (int j = i + 1; j < arr.length; j++) {

                // Store curr_sum = arr[i] + arr[j]
                int curr_sum = arr[i] + arr[j];

                // Check if X - curr_sum if present
                // in map
                if (map.containsKey(X - curr_sum)) {

                    // Store pair having map value
                    // X - curr_sum
                    pair p = map.get(X - curr_sum);

                    if (p.first != i && p.sec != i
                        && p.first != j && p.sec != j
                        && temp[p.first] == 0
                        && temp[p.sec] == 0 && temp[i] == 0
                        && temp[j] == 0) {

                        // Print the output
                        System.out.printf(
                            "%d,%d,%d,%d", arr[i], arr[j],
                            arr[p.first], arr[p.sec]);
                        temp[p.sec] = 1;
                        temp[i] = 1;
                        temp[j] = 1;
                        break;
                    }
                }
            }
        }
    }

    // Program for two Sum
    public static Map<Integer, pair> twoSum(int[] nums)
    {
        Map<Integer, pair> map = new HashMap<>();
        for (int i = 0; i < nums.length - 1; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                map.put(nums[i] + nums[j], new pair(i, j));
            }
        }
        return map;
    }

    // to store indices of two sum pair
    public static class pair {
        int first, sec;

        public pair(int first, int sec)
        {
            this.first = first;
            this.sec = sec;
        }
    }

    // Driver Code
    public static void main(String args[])
    {
        int[] arr = { 10, 20, 30, 40, 1, 2 };
        int n = arr.length;
        int X = 91;
        Map<Integer, pair> map = twoSum(arr);
      
        // Function call
        fourSum(X, arr, map);
    }
}

// This code is contributed by Likhita avl.
Python3
# Python3 program to find four  
# elements with the given sum

# Function to find 4 elements that
# add up to given sum 
def fourSum(X, arr, Map, N):
    
    temp = [0 for i in range(N)]
    
    # Iterate from 0 to length of arr 
    for i in range(N - 1):
        
        # Iterate from i + 1 to length of arr
        for j in range(i + 1, N):
            
            # Store curr_sum = arr[i] + arr[j] 
            curr_sum = arr[i] + arr[j]

            # Check if X - curr_sum if present 
            # in map 
            if (X - curr_sum) in Map:
                
                # Store pair having map value 
                # X - curr_sum 
                p = Map[X - curr_sum]

                if (p[0] != i and p[1] != i and
                    p[0] != j and p[1] != j and
                    temp[p[0]] == 0 and temp[p[1]] == 0 and 
                    temp[i] == 0 and temp[j] == 0):
                        
                    # Print the output 
                    print(arr[i], ",", arr[j], ",", 
                          arr[p[0]], ",", arr[p[1]], 
                          sep = "")
                          
                    temp[p[1]] = 1
                    temp[i] = 1
                    temp[j] = 1
                    break

# Function for two Sum 
def twoSum(nums, N):
    
    Map = {}
    
    for i in range(N - 1):
        for j in range(i + 1, N):
            Map[nums[i] + nums[j]] = []
            Map[nums[i] + nums[j]].append(i)
            Map[nums[i] + nums[j]].append(j)

    return Map

# Driver code
arr = [ 10, 20, 30, 40, 1, 2 ]
n = len(arr)
X = 91
Map = twoSum(arr, n)

# Function call 
fourSum(X, arr, Map, n)

# This code is contributed by avanitrachhadiya2155
C#
// C# program to find four  
// elements with the given sum 
using System;
using System.Collections.Generic;  
class GFG
{
    
    // Function to find 4 elements that add up to 
    // given sum 
    static void fourSum(int X, int[] arr, Dictionary<int, 
                        Tuple<int, int>> Map, int N) 
    { 
        int[] temp = new int[N]; 
     
        // Iterate from 0 to temp.length 
        for (int i = 0; i < N; i++) 
            temp[i] = 0; 
     
        // Iterate from 0 to arr.length 
        for (int i = 0; i < N - 1; i++) 
        { 
     
            // Iterate from i + 1 to arr.length 
            for (int j = i + 1; j < N; j++)
            { 
     
                // Store curr_sum = arr[i] + arr[j] 
                int curr_sum = arr[i] + arr[j]; 
     
                // Check if X - curr_sum if present 
                // in map 
                if (Map.ContainsKey(X - curr_sum)) 
                { 
     
                    // Store pair having map value 
                    // X - curr_sum 
                    Tuple<int, int> p = Map[X - curr_sum]; 
     
                    if (p.Item1 != i && p.Item2 != i 
                        && p.Item1 != j && p.Item2 != j 
                        && temp[p.Item1] == 0
                        && temp[p.Item2] == 0 && temp[i] == 0
                        && temp[j] == 0)
                    { 
     
                        // Print the output 
                        Console.Write(arr[i] + "," + arr[j] +
                                      "," + arr[p.Item1] + "," + 
                                      arr[p.Item2]);
                        temp[p.Item2] = 1; 
                        temp[i] = 1; 
                        temp[j] = 1; 
                        break; 
                    } 
                } 
            } 
        } 
    } 
     
    // Program for two Sum 
    static Dictionary<int, Tuple<int, int>> twoSum(int[] nums, int N) 
    { 
        Dictionary<int, Tuple<int, int>> Map = 
          new Dictionary<int, Tuple<int, int>>(); 
        for (int i = 0; i < N - 1; i++)
        { 
            for (int j = i + 1; j < N; j++)
            { 
                Map[nums[i] + nums[j]] = new Tuple<int, int>(i, j);
            } 
        } 
        return Map; 
    } 

  // Driver code
  static void Main() 
  {
    int[] arr = { 10, 20, 30, 40, 1, 2 }; 
    int n = arr.Length; 
    int X = 91;
    Dictionary<int, Tuple<int, int>> Map = twoSum(arr, n); 
     
    // Function call 
    fourSum(X, arr, Map, n); 
  }
}

// This code is contributed by divyeshrabadiya07
Javascript
<script>
// Javascript program to find four
// elements with the given sum

class pair
{
    constructor(first, sec)
    {
        this.first = first;
        this.sec = sec;
    }
}

// Function to find 4 elements that add up to
    // given sum
function fourSum(X, arr, map)
{
    let temp = new Array(arr.length);
 
        // Iterate from 0 to temp.length
        for (let i = 0; i < temp.length; i++)
            temp[i] = 0;
 
        // Iterate from 0 to arr.length
        for (let i = 0; i < arr.length - 1; i++) {
 
            // Iterate from i + 1 to arr.length
            for (let j = i + 1; j < arr.length; j++) {
 
                // Store curr_sum = arr[i] + arr[j]
                let curr_sum = arr[i] + arr[j];
 
                // Check if X - curr_sum if present
                // in map
                if (map.has(X - curr_sum)) {
 
                    // Store pair having map value
                    // X - curr_sum
                    let p = map.get(X - curr_sum);
 
                    if (p.first != i && p.sec != i
                        && p.first != j && p.sec != j
                        && temp[p.first] == 0
                        && temp[p.sec] == 0 && temp[i] == 0
                        && temp[j] == 0) {
 
                        // Print the output
                        document.write( arr[i]+","+arr[j]+","+
                            arr[p.first]+"," +arr[p.sec]);
                        temp[p.sec] = 1;
                        temp[i] = 1;
                        temp[j] = 1;
                        break;
                    }
                }
            }
        }
}

// Program for two Sum
function twoSum(nums)
{
     let map = new Map();
        for (let i = 0; i < nums.length - 1; i++) {
            for (let j = i + 1; j < nums.length; j++) {
                map.set(nums[i] + nums[j], new pair(i, j));
            }
        }
        return map;
}

// Driver Code
let arr=[10, 20, 30, 40, 1, 2];
let n = arr.length;
let X = 91;
let map = twoSum(arr);

// Function call
fourSum(X, arr, map);
                                
// This code is contributed by patel2127.
</script>

Output
20,30,40,1


Complexity Analysis:

  • Time complexity: O(n^2).
    Nested traversal is needed to store all pairs in the hash Map.
  • Auxiliary Space: O(n^2).
    All n*(n-1) pairs are stored in hash Map so the space required is O(n^2) and the temp array takes O(n) so space comes to O(n^2).

Without using extra spaces

C++
#include <bits/stdc++.h>
using namespace std;
void fourSum(vector<int>& nums, int target) 
{
    int n = nums.size();
    // sort the given array
    sort(nums.begin(), nums.end());
    // calculating the quadruplets
    for (int i = 0; i < n; i++) {
        // avoid the duplicates while moving i
        if (i > 0 && nums[i] == nums[i - 1]) continue;
        for (int j = i + 1; j < n; j++) {
            // avoid the duplicates while moving j
            if (j > i + 1 && nums[j] == nums[j - 1]) continue;
            // 2 pointers
            int k = j + 1;
            int l = n - 1;
            while (k < l) {
                long long sum = nums[i] + nums[j] + nums[k] + nums[l];
                if (sum == target) {
                    cout << nums[i] << " " << nums[j] << " " << nums[k] << " " << nums[l] << endl;
                    k++;
                    l--;
                    // skip the duplicates
                    while (k < l && nums[k] == nums[k - 1]) k++;
                    while (k < l && nums[l] == nums[l + 1]) l--;
                } else if (sum < target) {
                    k++;
                } else {
                    l--;
                }
            }
        }
    }
}
// Driver code
int main()
{
    vector<int> arr = { 10, 20, 30, 40, 1, 2 }; 
    int X = 91; 
    fourSum(arr, X); 
    return 0;
}

// This code is contributed by adarshsharadpandey23
Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class FourSum {
    public static List<List<Integer>> fourSum(int[] nums, int target) {
        Arrays.sort(nums);
        int n = nums.length;
        List<List<Integer>> result = new ArrayList<>();
        
        for (int i = 0; i < n; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            
            for (int j = i + 1; j < n; j++) {
                if (j > i + 1 && nums[j] == nums[j - 1]) {
                    continue;
                }
                
                int k = j + 1, l = n - 1;
                while (k < l) {
                    long total = (long) nums[i] + nums[j] + nums[k] + nums[l];
                    if (total == target) {
                        result.add(Arrays.asList(nums[i], nums[j], nums[k], nums[l]));
                        k++;
                        l--;
                        while (k < l && nums[k] == nums[k - 1]) {
                            k++;
                        }
                        while (k < l && nums[l] == nums[l + 1]) {
                            l--;
                        }
                    } else if (total < target) {
                        k++;
                    } else {
                        l--;
                    }
                }
            }
        }
        
        return result;
    }
    
    public static void main(String[] args) {
        int[] nums = {10, 2, 3, 4, 5, 9, 7, 8};
        int target = 23;
        System.out.println(fourSum(nums, target));
    }
}
Python
def four_sum(nums, target):
    nums.sort()
    n = len(nums)
    result = []
    
    for i in range(n):
        if i > 0 and nums[i] == nums[i - 1]:
            continue
        
        for j in range(i + 1, n):
            if j > i + 1 and nums[j] == nums[j - 1]:
                continue
            
            k, l = j + 1, n - 1
            while k < l:
                total = nums[i] + nums[j] + nums[k] + nums[l]
                if total == target:
                    result.append([nums[i], nums[j], nums[k], nums[l]])
                    k += 1
                    l -= 1
                    while k < l and nums[k] == nums[k - 1]:
                        k += 1
                    while k < l and nums[l] == nums[l + 1]:
                        l -= 1
                elif total < target:
                    k += 1
                else:
                    l -= 1
    
    return result

# Example usage
nums = [10, 2, 3, 4, 5, 9, 7, 8]
target = 23
print(four_sum(nums, target))
C#
using System;
using System.Collections.Generic;

public class Program
{
    public static List<List<int>> FourSum(int[] nums, int target)
    {
        Array.Sort(nums);
        int n = nums.Length;
        List<List<int>> result = new List<List<int>>();
        
        for (int i = 0; i < n; i++)
        {
            if (i > 0 && nums[i] == nums[i - 1])
            {
                continue;
            }
            
            for (int j = i + 1; j < n; j++)
            {
                if (j > i + 1 && nums[j] == nums[j - 1])
                {
                    continue;
                }
                
                int k = j + 1, l = n - 1;
                while (k < l)
                {
                    long total = (long)nums[i] + nums[j] + nums[k] + nums[l];
                    if (total == target)
                    {
                        result.Add(new List<int> { nums[i], nums[j], nums[k], nums[l] });
                        k++;
                        l--;
                        while (k < l && nums[k] == nums[k - 1])
                        {
                            k++;
                        }
                        while (k < l && nums[l] == nums[l + 1])
                        {
                            l--;
                        }
                    }
                    else if (total < target)
                    {
                        k++;
                    }
                    else
                    {
                        l--;
                    }
                }
            }
        }
        
        return result;
    }

    public static void Main()
    {
        int[] nums = { 10, 2, 3, 4, 5, 9, 7, 8 };
        int target = 23;
        List<List<int>> result = FourSum(nums, target);
        foreach (List<int> quadruplet in result)
        {
            Console.WriteLine(string.Join(" ", quadruplet));
        }
    }
}
// Contributed by adarshsharadpandey
JavaScript
function fourSum(nums, target) {
    nums.sort((a, b) => a - b);
    const n = nums.length;
    const result = [];
    
    for (let i = 0; i < n; i++) {
        if (i > 0 && nums[i] === nums[i - 1]) {
            continue;
        }
        
        for (let j = i + 1; j < n; j++) {
            if (j > i + 1 && nums[j] === nums[j - 1]) {
                continue;
            }
            
            let k = j + 1, l = n - 1;
            while (k < l) {
                const total = nums[i] + nums[j] + nums[k] + nums[l];
                if (total === target) {
                    result.push([nums[i], nums[j], nums[k], nums[l]]);
                    k++;
                    l--;
                    while (k < l && nums[k] === nums[k - 1]) {
                        k++;
                    }
                    while (k < l && nums[l] === nums[l + 1]) {
                        l--;
                    }
                } else if (total < target) {
                    k++;
                } else {
                    l--;
                }
            }
        }
    }
    
    return result;
}

// Example usage
const nums = [10, 2, 3, 4, 5, 9, 7, 8];
const target = 23;
console.log(fourSum(nums, target));


Output :

1 20 30 40


Complexity Analysis:

Time complexity: O(n^2).

Auxiliary Space: O(1).



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads