Open In App

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

Last Updated : 24 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

C++
#include <bits/stdc++.h>
using namespace std;

bool check4Sum(vector<int>& arr, int target) {
    int n = arr.size();
    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++)
                    if (arr[i] + arr[j] + arr[k] + arr[l] == target)
                       return true;

    return false;
}

int main() {
    vector<int> arr = {1, 1, 1, 1, 1};
    int target = 4;
    cout << (check4Sum(arr, target)? "True" : "False");
    return 0;
}
C
#include <stdio.h>
#include <stdbool.h>

bool check4Sum(int arr[], int n, int target) {
    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++)
                    if (arr[i] + arr[j] + arr[k] + arr[l] == target)
                        return true;

    return false;
}

int main() {
    int arr[] = {1, 1, 1, 1, 1};
    int target = 4;
    int n = sizeof(arr) / sizeof(arr[0]);
    
    printf("%s", check4Sum(arr, n, target) ? "True" : "False");
    return 0;
}
Java
class GfG {

    static boolean check4Sum(int[] arr, int target) {
        int n = arr.length;
        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++)
                        if (arr[i] + arr[j] + arr[k] + arr[l] == target)
                            return true;

        return false;
    }

    public static void main(String[] args) {
        int[] arr = {1, 1, 1, 1, 1};
        int target = 4;
        
        System.out.println(check4Sum(arr, target) ? "True" : "False");
    }
}
Python
def check4Sum(arr, target):
    n = len(arr)
    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):
                    if arr[i] + arr[j] + arr[k] + arr[l] == target:
                        return True
    return False

# Driver code
arr = [1, 1, 1, 1, 1]
target = 4

print("True" if check4Sum(arr, target) else "False")
C#
using System;

class GfG
{
    static bool check4Sum(int[] arr, int target) {
        int n = arr.Length;
        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++)
                        if (arr[i] + arr[j] + arr[k] + arr[l] == target)
                            return true;

        return false;
    }

    static void Main() {
        int[] arr = {1, 1, 1, 1, 1};
        int target = 4;

        Console.WriteLine(check4Sum(arr, target) ? "True" : "False");
    }
}
JavaScript
function check4Sum(arr, target) {
    let n = arr.length;
    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++)
                    if (arr[i] + arr[j] + arr[k] + arr[l] === target)
                        return true;
    return false;
}

// Driver code
const arr = [1, 1, 1, 1, 1];
const target = 4;

console.log(check4Sum(arr, target) ? "True" : "False");

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.

C++
#include <bits/stdc++.h>
using namespace std;

bool check4Sum(vector<int>& arr, int target) {
    vector<vector<int>> res;
    int n = arr.size();

    // Sort the array in increasing order so that
    // we can later apply two pointer tecnique
    sort(arr.begin(), arr.end());

    // Fix the first two elements one by one
    for (int i = 0; i < n - 3; i++) {
        for (int j = i + 1; j < n - 2; j++) {

            // Find the remaining two elements
            // using two pointers
            int l = j + 1;
            int r = n - 1;
            while (l < r) {
                int sum = arr[i] + arr[j] + arr[l] + arr[r];

                if (sum == target) {
                    return true;
                    l++;
                    r--;
                } else if (sum < target) {
                    l++;
                } else {
                    r--;
                }
            }
        }
    }

    return false;
}

int main() {
    vector<int> arr = {1, 1, 1, 1, 1};
    int target = 4;
    cout << (check4Sum(arr, target)? "True" : "False");
    return 0;
}
C
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

// Comparison function for qsort
int cmpfunc(const void *a, const void *b) {
    return (*(int *)a - *(int *)b);
}

bool check4Sum(int arr[], int n, int target) {
    
    // Sort the array in increasing order so that
    // we can later apply two pointer technique
    qsort(arr, n, sizeof(int), cmpfunc);

    // Fix the first two elements one by one
    for (int i = 0; i < n - 3; i++) {
        for (int j = i + 1; j < n - 2; j++) {

            // Find the remaining two elements
            // using two pointers
            int l = j + 1;
            int r = n - 1;
            while (l < r) {
                int sum = arr[i] + arr[j] + arr[l] + arr[r];

                if (sum == target) {
                    return true;
                    l++;
                    r--;
                } else if (sum < target) {
                    l++;
                } else {
                    r--;
                }
            }
        }
    }

    return false;
}

int main() {
    int arr[] = {1, 1, 1, 1, 1};
    int target = 4;
    int n = sizeof(arr) / sizeof(arr[0]);

    printf("%s", check4Sum(arr, n, target) ? "True" : "False");
    return 0;
}
Java
import java.util.Arrays;

class GfG {

    static boolean check4Sum(int[] arr, int target) {
        int n = arr.length;

        // Sort the array in increasing order so that
        // we can later apply two pointer technique
        Arrays.sort(arr);

        // Fix the first two elements one by one
        for (int i = 0; i < n - 3; i++) {
            for (int j = i + 1; j < n - 2; j++) {

                // Find the remaining two elements
                // using two pointers
                int l = j + 1;
                int r = n - 1;
                while (l < r) {
                    int sum = arr[i] + arr[j] + arr[l] + arr[r];

                    if (sum == target) {
                        return true;
                    } else if (sum < target) {
                        l++;
                    } else {
                        r--;
                    }
                }
            }
        }

        return false;
    }

    public static void main(String[] args) {
        int[] arr = {1, 1, 1, 1, 1};
        int target = 4;

        System.out.println(check4Sum(arr, target) ? "True" : "False");
    }
}
Python
def check4Sum(arr, target):
    n = len(arr)

    # Sort the array in increasing order so that
    # we can later apply two pointer technique
    arr.sort()

    # Fix the first two elements one by one
    for i in range(n - 3):
        for j in range(i + 1, n - 2):

            # Find the remaining two elements
            # using two pointers
            l, r = j + 1, n - 1
            while l < r:
                total = arr[i] + arr[j] + arr[l] + arr[r]

                if total == target:
                    return True
                elif total < target:
                    l += 1
                else:
                    r -= 1

    return False

# Driver code
arr = [1, 1, 1, 1, 1]
target = 4

print("True" if check4Sum(arr, target) else "False")
C#
using System;

class GfG
{
    static bool check4Sum(int[] arr, int target) {
        int n = arr.Length;

        // Sort the array in increasing order so that
        // we can later apply two pointer technique
        Array.Sort(arr);

        // Fix the first two elements one by one
        for (int i = 0; i < n - 3; i++) {
            for (int j = i + 1; j < n - 2; j++) {

                // Find the remaining two elements
                // using two pointers
                int l = j + 1;
                int r = n - 1;
                while (l < r) {
                    int sum = arr[i] + arr[j] + arr[l] + arr[r];

                    if (sum == target) {
                        return true;
                    } else if (sum < target) {
                        l++;
                    } else {
                        r--;
                    }
                }
            }
        }

        return false;
    }

    static void Main() {
        int[] arr = {1, 1, 1, 1, 1};
        int target = 4;

        Console.WriteLine(check4Sum(arr, target) ? "True" : "False");
    }
}
JavaScript
function check4Sum(arr, target) {
    const n = arr.length;

    // Sort the array in increasing order so that
    // we can later apply two pointer technique
    arr.sort((a, b) => a - b);

    // Fix the first two elements one by one
    for (let i = 0; i < n - 3; i++) {
        for (let j = i + 1; j < n - 2; j++) {

            // Find the remaining two elements
            // using two pointers
            let l = j + 1, r = n - 1;
            while (l < r) {
                const sum = arr[i] + arr[j] + arr[l] + arr[r];

                if (sum === target) {
                    return true;
                } else if (sum < target) {
                    l++;
                } else {
                    r--;
                }
            }
        }
    }

    return false;
}

// Driver code
const arr = [1, 1, 1, 1, 1];
const target = 4;

console.log(check4Sum(arr, target) ? "True" : "False");

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.

C++
#include <unordered_map>
#include <iostream>
#include <vector>
using namespace std;

// The function finds four elements with the given sum target
bool check4Sum(const vector<int>& arr, int target) {
    int n = arr.size();

    // Store sums of all pairs in a hash map
    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 
    // target - (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 target - sum is present in the hash map
            if (mp.find(target - sum) != mp.end()) {
                pair<int, int> p = mp[target - sum];

                // Check that all elements are different array elements 
                // (Same element should not be cosnidered twice)
                if (p.first != i && p.first != j && p.second != i && p.second != j)
                    return true;
            }
        }
    }
    return false;
}

int main() {
    vector<int> arr = {1, 1, 1, 1, 1};
    int target = 4;
    cout << (check4Sum(arr, target)? "True" : "False");
    return 0;
}
Java
import java.util.HashMap;

class GfG {

    // The function finds four elements with the given sum target
    static boolean check4Sum(int[] arr, int target) {
        int n = arr.length;

        // Store sums of all pairs in a hash map
        HashMap<Integer, int[]> mp = new HashMap<>();
        for (int i = 0; i < n - 1; i++) {
            for (int j = i + 1; j < n; j++) {
                mp.put(arr[i] + arr[j], new int[]{i, j});
            }
        }

        // Traverse through all pairs and search for 
        // target - (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 target - sum is present in the hash map
                if (mp.containsKey(target - sum)) {
                    int[] p = mp.get(target - sum);

                    // Check that all elements are different array elements 
                    if (p[0] != i && p[0] != j && p[1] != i && p[1] != j)
                        return true;
                }
            }
        }

        return false;
    }

    public static void main(String[] args) {
        int[] arr = {1, 1, 1, 1, 1};
        int target = 4;
        
        System.out.println(check4Sum(arr, target) ? "True" : "False");
    }
}
Python
def check4Sum(arr, target):
    n = len(arr)

    # Store sums of all pairs in a hash map
    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 
    # target - (current pair sum)
    for i in range(n - 1):
        for j in range(i + 1, n):
            sum_val = arr[i] + arr[j]

            # If target - sum is present in the hash map
            if target - sum_val in mp:
                p = mp[target - sum_val]

                # Check that all elements are different array elements 
                if p[0] != i and p[0] != j and p[1] != i and p[1] != j:
                    return True

    return False

# Driver code
arr = [1, 1, 1, 1, 1]
target = 4

print("True" if check4Sum(arr, target) else "False")
C#
using System;
using System.Collections.Generic;

class GfG
{
    // The function finds four elements with the given sum target
    static bool check4Sum(int[] arr, int target) {
        int n = arr.Length;

        // Store sums of all pairs in a hash map
        Dictionary<int, int[]> mp = new Dictionary<int, int[]>();
        for (int i = 0; i < n - 1; i++) {
            for (int j = i + 1; j < n; j++) {
                mp[arr[i] + arr[j]] = new int[] { i, j };
            }
        }

        // Traverse through all pairs and search for 
        // target - (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 target - sum is present in the hash map
                if (mp.ContainsKey(target - sum)) {
                    int[] p = mp[target - sum];

                    // Check that all elements are different array elements 
                    if (p[0] != i && p[0] != j && p[1] != i && p[1] != j)
                        return true;
                }
            }
        }

        return false;
    }

    static void Main() {
        int[] arr = {1, 1, 1, 1, 1};
        int target = 4;

        Console.WriteLine(check4Sum(arr, target) ? "True" : "False");
    }
}
JavaScript
function check4Sum(arr, target) {
    const n = arr.length;

    // Store sums of all pairs in a hash map
    const mp = {};
    for (let i = 0; i < n - 1; i++) {
        for (let j = i + 1; j < n; j++) {
            mp[arr[i] + arr[j]] = [i, j];
        }
    }

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

            // If target - sum is present in the hash map
            if (mp[target - sum]) {
                const p = mp[target - sum];

                // Check that all elements are different array elements 
                if (p[0] !== i && p[0] !== j && p[1] !== i && p[1] !== j)
                    return true;
            }
        }
    }

    return false;
}

// Driver code
const arr = [1, 1, 1, 1, 1];
const target = 4;

console.log(check4Sum(arr, target) ? "True" : "False");

Output
True



Next Article

Similar Reads