Find four elements that sum to a given value | Set 1 (n^3 solution) - GeeksforGeeks

24 Mar, 2021
Given an array of integers, find all combination of four elements in the array whose sum is equal to a given value X. For example, if the given array is {10, 2, 3, 4, 5, 9, 7, 8} and X = 23, then your function should print “3 5 7 8” (3 + 5 + 7 + 8 = 23). 
A Naive Solution is to generate all possible quadruples and compare the sum of every quadruple with X. The following code implements this simple method using four nested loops  
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program for naive solution to// print all combination of 4 elements// in A[] with sum equal to X#include <bits/stdc++.h>using namespace std; /* A naive solution to print all combinationof 4 elements in A[]with sum equal to X */void findFourElements(int A[], int n, int X){     // Fix the first element and find other threefor (int i = 0; i < n - 3; i++){    // Fix the second element and find other two    for (int j = i + 1; j < n - 2; j++)    {                 // Fix the third element and find the fourth        for (int k = j + 1; k < n - 1; k++)        {            // find the fourth            for (int l = k + 1; l < n; l++)            if (A[i] + A[j] + A[k] + A[l] == X)                cout << A[i] <<", " << A[j]                     << ", " << A[k] << ", " << A[l];        }    }}} // Driver Codeint main(){    int A[] = {10, 20, 30, 40, 1, 2};    int n = sizeof(A) / sizeof(A[0]);    int X = 91;    findFourElements (A, n, X);    return 0;} // This code is contributed// by Akanksha Rai
#include <stdio.h> /* A naive solution to print all combination of 4 elements in A[]  with sum equal to X */void findFourElements(int A[], int n, int X){  // Fix the first element and find other three  for (int i = 0; i < n-3; i++)  {    // Fix the second element and find other two    for (int j = i+1; j < n-2; j++)    {      // Fix the third element and find the fourth      for (int k = j+1; k < n-1; k++)      {        // find the fourth        for (int l = k+1; l < n; l++)           if (A[i] + A[j] + A[k] + A[l] == X)              printf("%d, %d, %d, %d", A[i], A[j], A[k], A[l]);      }    }  }} // Driver program to test above functionint main(){    int A[] = {10, 20, 30, 40, 1, 2};    int n = sizeof(A) / sizeof(A[0]);    int X = 91;    findFourElements (A, n, X);    return 0;}
class FindFourElements{     /* A naive solution to print all combination of 4 elements in A[]       with sum equal to X */    void findFourElements(int A[], int n, int X)    {        // Fix the first element and find other three        for (int i = 0; i < n - 3; i++)        {            // Fix the second element and find other two            for (int j = i + 1; j < n - 2; j++)            {                // Fix the third element and find the fourth                for (int k = j + 1; k < n - 1; k++)                {                    // find the fourth                    for (int l = k + 1; l < n; l++)                    {                        if (A[i] + A[j] + A[k] + A[l] == X)                            System.out.print(A[i]+" "+A[j]+" "+A[k]                                                                 +" "+A[l]);                    }                }            }        }    }     // Driver program to test above functions    public static void main(String[] args)    {        FindFourElements findfour = new FindFourElements();        int A[] = {10, 20, 30, 40, 1, 2};        int n = A.length;        int X = 91;        findfour.findFourElements(A, n, X);    }}
# A naive solution to print all combination# of 4 elements in A[] with sum equal to Xdef findFourElements(A, n, X):         # Fix the first element and find    # other three    for i in range(0,n-3):                 # Fix the second element and        # find other two        for j in range(i+1,n-2):                         # Fix the third element            # and find the fourth            for k in range(j+1,n-1):                                 # find the fourth                for l in range(k+1,n):                                         if A[i] + A[j] + A[k] + A[l] == X:                        print ("%d, %d, %d, %d"                        %( A[i], A[j], A[k], A[l])) # Driver program to test above functionA = [10, 2, 3, 4, 5, 9, 7, 8]n = len(A)X = 23findFourElements (A, n, X) # This code is contributed by shreyanshi_arun
// C# program for naive solution to// print all combination of 4 elements// in A[] with sum equal to Xusing System; class FindFourElements{    void findFourElements(int []A, int n, int X)    {        // Fix the first element and find other three        for (int i = 0; i < n - 3; i++)        {            // Fix the second element and find other two            for (int j = i + 1; j < n - 2; j++)            {                // Fix the third element and find the fourth                for (int k = j + 1; k < n - 1; k++)                {                    // find the fourth                    for (int l = k + 1; l < n; l++)                    {                        if (A[i] + A[j] + A[k] + A[l] == X)                        Console.Write(A[i] + " " + A[j] +                                " " + A[k] + " " + A[l]);                    }                }            }        }    }     // Driver program to test above functions    public static void Main()    {        FindFourElements findfour = new FindFourElements();        int []A = {10, 20, 30, 40, 1, 2};        int n = A.Length;        int X = 91;        findfour.findFourElements(A, n, X);    }} // This code is contributed by nitin mittal
<?php/* A naive solution to print all combinationof 4 elements in A[] with sum equal to X */ function findFourElements($A, $n, $X){    // Fix the first element and find other    // three    for ($i = 0; $i < $n-3; $i++)    {        // Fix the second element and find        // other two        for ($j = $i+1; $j < $n-2; $j++)        {            // Fix the third element and            // find the fourth            for ($k = $j+1; $k < $n-1; $k++)            {                // find the fourth                for ($l = $k+1; $l < $n; $l++)                    if ($A[$i] + $A[$j] +                        $A[$k] + $A[$l] == $X)                                                 echo $A[$i], ", " , $A[$j],                        ", ", $A[$k], ", ", $A[$l];            }        }    }} // Driver program to test above function    $A = array (10, 20, 30, 40, 1, 2);    $n = sizeof($A) ;    $X = 91;    findFourElements ($A, $n, $X);     // This code is contributed by m_kit?>
<script> // Javascript program for the above approach /* A naive solution to print all combinationof 4 elements in A[]with sum equal to X */function findFourElements(A, n, X){     // Fix the first element and find other threefor (let i = 0; i < n - 3; i++){    // Fix the second element and find other two    for (let j = i + 1; j < n - 2; j++)    {                 // Fix the third element and find the fourth        for (let k = j + 1; k < n - 1; k++)        {            // find the fourth            for (let l = k + 1; l < n; l++)            if (A[i] + A[j] + A[k] + A[l] == X)                document.write(A[i]+", "+A[j]+", "+A[k] +", "+A[l]);        }    }}} // Driver Code     let A = [10, 20, 30, 40, 1, 2];    let n = A.length;    let X = 91;    findFourElements (A, n, X); </script>
Output:
20, 30, 40, 1
Time Complexity: O(n^4)The time complexity can be improved to O(n^3) with the use of sorting as a preprocessing step, and then using method 1 of this post to reduce a loop.Following are the detailed steps. 1) Sort the input array. 2) Fix the first element as A[i] where i is from 0 to n–3. After fixing the first element of quadruple, fix the second element as A[j] where j varies from i+1 to n-2. Find remaining two elements in O(n) time, using the method 1 of this post Following is the implementation of O(n^3) solution.  
C++
C
Java
Python 3
C#
PHP
Javascript
// C++ program for to  print all combination// of 4 elements in A[] with sum equal to X#include<bits/stdc++.h>using namespace std; /* Following function is neededfor library function qsort(). */int compare (const void *a, const void * b){    return ( *(int *)a - *(int *)b );} /* A sorting based solution to printall combination of 4 elements in A[]with sum equal to X */void find4Numbers(int A[], int n, int X){    int l, r;     // Sort the array in increasing    // order, using library function    // for quick sort    qsort (A, n, sizeof(A[0]), compare);     /* Now fix the first 2 elements    one by one and find    the other two elements */    for (int i = 0; i < n - 3; i++)    {        for (int j = i+1; j < n - 2; j++)        {            // Initialize two variables as            // indexes of the first and last            // elements in the remaining elements            l = j + 1;            r = n-1;             // To find the remaining two            // elements, move the index            // variables (l & r) toward each other.            while (l < r)            {                if( A[i] + A[j] + A[l] + A[r] == X)                {                    cout << A[i]<<", " << A[j] <<                        ", " << A[l] << ", " << A[r];                    l++; r--;                }                else if (A[i] + A[j] + A[l] + A[r] < X)                    l++;                else // A[i] + A[j] + A[l] + A[r] > X                    r--;            } // end of while        } // end of inner for loop    } // end of outer for loop} /* Driver code */int main(){    int A[] = {1, 4, 45, 6, 10, 12};    int X = 21;    int n = sizeof(A) / sizeof(A[0]);    find4Numbers(A, n, X);    return 0;} // This code is contributed by rathbhupendra
# include <stdio.h># include <stdlib.h> /* Following function is needed for library function qsort(). Refer   http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/ */int compare (const void *a, const void * b){  return ( *(int *)a - *(int *)b ); } /* A sorting based solution to print all combination of 4 elements in A[]   with sum equal to X */void find4Numbers(int A[], int n, int X){    int l, r;     // Sort the array in increasing order, using library    // function for quick sort    qsort (A, n, sizeof(A[0]), compare);     /* Now fix the first 2 elements one by one and find       the other two elements */    for (int i = 0; i < n - 3; i++)    {        for (int j = i+1; j < n - 2; j++)        {            // Initialize two variables as indexes of the first and last            // elements in the remaining elements            l = j + 1;            r = n-1;             // To find the remaining two elements, move the index            // variables (l & r) toward each other.            while (l < r)            {                if( A[i] + A[j] + A[l] + A[r] == X)                {                   printf("%d, %d, %d, %d", A[i], A[j],                                           A[l], A[r]);                   l++; r--;                }                else if (A[i] + A[j] + A[l] + A[r] < X)                    l++;                else // A[i] + A[j] + A[l] + A[r] > X                    r--;            } // end of while        } // end of inner for loop    } // end of outer for loop} /* Driver program to test above function */int main(){    int A[] = {1, 4, 45, 6, 10, 12};    int X = 21;    int n = sizeof(A)/sizeof(A[0]);    find4Numbers(A, n, X);    return 0;}
import java.util.Arrays;  class FindFourElements{    /* A sorting based solution to print all combination of 4 elements in A[]       with sum equal to X */    void find4Numbers(int A[], int n, int X)    {        int l, r;         // Sort the array in increasing order, using library        // function for quick sort        Arrays.sort(A);         /* Now fix the first 2 elements one by one and find           the other two elements */        for (int i = 0; i < n - 3; i++)        {            for (int j = i + 1; j < n - 2; j++)            {                // Initialize two variables as indexes of the first and last                // elements in the remaining elements                l = j + 1;                r = n - 1;                 // To find the remaining two elements, move the index                // variables (l & r) toward each other.                while (l < r)                {                    if (A[i] + A[j] + A[l] + A[r] == X)                    {                        System.out.println(A[i]+" "+A[j]+" "+A[l]+" "+A[r]);                        l++;                        r--;                    }                    else if (A[i] + A[j] + A[l] + A[r] < X)                        l++;                    else // A[i] + A[j] + A[l] + A[r] > X                        r--;                } // end of while            } // end of inner for loop        } // end of outer for loop    }     // Driver program to test above functions    public static void main(String[] args)    {        FindFourElements findfour = new FindFourElements();        int A[] = {1, 4, 45, 6, 10, 12};        int n = A.length;        int X = 21;        findfour.find4Numbers(A, n, X);    }} // This code has been contributed by Mayank Jaiswal
# A sorting based solution to print all combination# of 4 elements in A[] with sum equal to Xdef find4Numbers(A, n, X):     # Sort the array in increasing order,    # using library function for quick sort    A.sort()     # Now fix the first 2 elements one by    # one and find the other two elements    for i in range(n - 3):        for j in range(i + 1, n - 2):                         # Initialize two variables as indexes            # of the first and last elements in            # the remaining elements            l = j + 1            r = n - 1             # To find the remaining two elements,            # move the index variables (l & r)            # toward each other.            while (l < r):                if(A[i] + A[j] + A[l] + A[r] == X):                    print(A[i], ",", A[j], ",",                          A[l], ",", A[r])                    l += 1                    r -= 1                                 elif (A[i] + A[j] + A[l] + A[r] < X):                    l += 1                else: # A[i] + A[j] + A[l] + A[r] > X                    r -= 1 # Driver Codeif __name__ == "__main__":         A = [1, 4, 45, 6, 10, 12]    X = 21    n = len(A)    find4Numbers(A, n, X) # This code is contributed by ita_c
// C# program for to  print all combination// of 4 elements in A[] with sum equal to Xusing System; class FindFourElements{    // A sorting based solution to print all    // combination of 4 elements in A[] with    // sum equal to X    void find4Numbers(int []A, int n, int X)    {        int l, r;         // Sort the array in increasing order,        // using library function for quick sort        Array.Sort(A);         /* Now fix the first 2 elements one by one           and find the other two elements */        for (int i = 0; i < n - 3; i++)        {            for (int j = i + 1; j < n - 2; j++)            {                // Initialize two variables as indexes of                // the first and last elements in the                // remaining elements                l = j + 1;                r = n - 1;                 // To find the remaining two elements, move the                // index variables (l & r) toward each other.                while (l < r)                {                    if (A[i] + A[j] + A[l] + A[r] == X)                    {                        Console.Write(A[i] + " " + A[j] +                                " " + A[l] + " " + A[r]);                        l++;                        r--;                    }                    else if (A[i] + A[j] + A[l] + A[r] < X)                        l++;                                             else // A[i] + A[j] + A[l] + A[r] > X                        r--;                                         } // end of while                             } // end of inner for loop                     } // end of outer for loop    }     // Driver program to test above functions    public static void Main()    {        FindFourElements findfour = new FindFourElements();        int []A = {1, 4, 45, 6, 10, 12};        int n = A.Length;        int X = 21;        findfour.find4Numbers(A, n, X);    }} // This code has been contributed by nitin mittal
<?php// PHP program for to print all// combination of 4 elements in// A[] with sum equal to X // A sorting based solution to// print all combination of 4// elements in A[] with sum// equal to Xfunction find4Numbers($A, $n, $X){    $l; $r;     // Sort the array in increasing    // order, using library function    // for quick sort    sort($A);     // Now fix the first 2 elements    // one by one and find the other    // two elements    for ($i = 0; $i < $n - 3; $i++)    {        for ($j = $i + 1; $j < $n - 2; $j++)        {            // Initialize two variables            // as indexes of the first            // and last elements in the            // remaining elements            $l = $j + 1;            $r = $n - 1;             // To find the remaining two            // elements, move the index            // variables (l & r) towards            // each other.            while ($l < $r)            {                if ($A[$i] + $A[$j] +                    $A[$l] + $A[$r] == $X)                {                    echo $A[$i] , " " , $A[$j] ,                                  " " , $A[$l] ,                                  " " , $A[$r];                    $l++;                    $r--;                }                else if ($A[$i] + $A[$j] +                         $A[$l] + $A[$r] < $X)                    $l++;                                     // A[i] + A[j] + A[l] + A[r] > X                else                    $r--;                                 }        }    }} // Driver Code$A = array(1, 4, 45, 6, 10, 12);$n = count($A);$X = 21;find4Numbers($A, $n, $X); // This code is contributed// by nitin mittal?>
<script>         /* A sorting based solution to print all combination of 4 elements in A[]       with sum equal to X */    function find4Numbers(A,n,X)    {                 let l, r;        // Sort the array in increasing order, using library        // function for quick sort        A.sort(function(a, b){return a - b});                 /* Now fix the first 2 elements one by one and find           the other two elements */        for (let i = 0; i < n - 3; i++)        {            for (let j = i + 1; j < n - 2; j++)            {                // Initialize two variables as indexes of the first and last                // elements in the remaining elements                l = j + 1;                r = n - 1;                  // To find the remaining two elements, move the index                // variables (l & r) toward each other.                while (l < r)                {                    if (A[i] + A[j] + A[l] + A[r] == X)                    {                        document.write(A[i]+" "+A[j]+" "+A[l]+" "+A[r]+"<br>");                        l++;                        r--;                    }                    else if ((A[i] + A[j] + A[l] + A[r]) < X)                    {                           l++;                    }                    else // A[i] + A[j] + A[l] + A[r] > X                    {                        r--;                    }                } // end of while            }    // end of inner for loop        }// end of outer for loop    }         // Driver program to test above functions    let A= [1, 4, 45, 6, 10, 12];    let n = A.length;    let X = 21;         find4Numbers(A, n, X)         // This code is contributed by rag2127     </script>
Output : 
1, 4, 6, 10
Time Complexity : O(n^3) 
YouTubeGeeksforGeeks501K subscribersFind four elements that sum to a given value | Set 1 (n^3 solution) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:28•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=0fo7goi2GEg" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This problem can also be solved in O(n^2Logn) complexity. Please refer below post for detailsFind four elements that sum to a given value | Set 2 ( O(n^2Logn) Solution)Please write comments if you find any of the above codes/algorithms incorrect, or find other ways to solve the same problem. 
nitin mittal
jit_t
vt_m
ukasp
Akanksha_Rai
rathbhupendra
shubham_singh
souravghosh0416
rag2127
Amazon
OYO Rooms
two-pointer-algorithm
Arrays
Searching
Amazon
OYO Rooms
two-pointer-algorithm
Arrays
Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Introduction to Arrays
Linear Search
Binary Search
Linear Search
Maximum and minimum of an array using minimum number of comparisons
Find the Missing Number
K'th Smallest/Largest Element in Unsorted Array | Set 1