Open In App
Related Articles

Find four elements that sum to a given value | Set 3 (Hashmap)

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Given an array of integers, Check if there exist four elements at different indexes in the array whose sum is equal to a given value k. For example, if the given array is {1 5 1 0 6 0} and k = 7, then your function should print “YES” as (1+5+1+0=7).

Examples:

Input  : arr[] = {1 5 1 0 6 0} 
             k = 7
Output : YES

Input :  arr[] = {38 7 44 42 28 16 10 37 
                  33 2 38 29 26 8 25} 
            k = 22
Output : NO

We have discussed different solutions in below two sets. Find four elements that sum to a given value | Set 1 (n^3 solution) Find four elements that sum to a given value | Set 2 ( O(n^2Logn) Solution) In this post, an optimized solution is discussed that works in O(n2) on average. The idea is to create a hashmap to store pair sums.

Loop i = 0 to n-1 :
 Loop j = i + 1 to n-1  
   calculate sum = arr[i] + arr[j]
     If (k-sum) exist in hash 
      a) Check in hash table for all
         pairs of indexes which form
         (k-sum).
      b) If there is any pair with no 
         common indexes.
           return true 
    Else update hash table
    EndLoop;
EndLoop;

Implementation:

CPP

// C++ program to find if there exist 4 elements
// with given sum
#include <bits/stdc++.h>
using namespace std;
 
// function to check if there exist four
// elements whose sum is equal to k
bool findfour(int arr[], int n, int k)
{
    // map to store sum and indexes for
    // a pair sum
    unordered_map<int, vector<pair<int, int> > > hash;
 
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
 
            // calculate the sum of each pair
            int sum = arr[i] + arr[j];
 
            // if k-sum exist in map
            if (hash.find(k - sum) != hash.end()) {
                auto num = hash.find(k - sum);
                vector<pair<int, int> > v = num->second;
 
                // check for index coincidence as if
                // there is a common that means all
                // the four numbers are not from
                // different indexes and one of the
                // index is repeated
                for (int k = 0; k < num->second.size();
                     k++) {
 
                    pair<int, int> it = v[k];
 
                    // if all indexes are different then
                    // it means four number exist
                    // set the flag and break the loop
                    if (it.first != i && it.first != j
                        && it.second != i && it.second != j)
                        return true;
                }
            }
 
            // store the sum and index pair in hashmap
            hash[sum].push_back(make_pair(i, j));
        }
    }
    hash.clear();
    return false;
}
 
// Driver code
int main()
{
    int k = 7;
    int arr[] = { 1, 5, 1, 0, 6, 0 };
    int n = sizeof(arr) / sizeof(arr[0]);
    if (findfour(arr, n, k))
        cout << "YES" << endl;
    else
        cout << "NO" << endl;
    return 0;
}

                    

Java

import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
 
public class Gfg {
    public static boolean findfour(int[] arr, int n, int k)
    {
        Map<Integer, Vector<Pair> > hash = new HashMap<>();
 
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                // calculate the sum of each pair
                int sum = arr[i] + arr[j];
 
                // if k-sum exists in map
                if (hash.containsKey(k - sum)) {
                    Vector<Pair> v = hash.get(k - sum);
 
                    for (int kk = 0; kk < v.size(); kk++) {
                        Pair it = v.get(kk);
                        if (it.first != i && it.first != j
                            && it.second != i
                            && it.second != j) {
                            return true;
                        }
                    }
                }
 
                Vector<Pair> vec = new Vector<>();
                vec.add(new Pair(i, j));
                hash.put(sum, vec);
            }
        }
 
        hash.clear();
        return false;
    }
 
    public static void main(String[] args)
    {
        int k = 7;
        int[] arr = { 1, 5, 1, 0, 6, 0 };
        int n = arr.length;
        if (findfour(arr, n, k)) {
            System.out.println("YES");
        }
        else {
            System.out.println("NO");
        }
    }
}
 
class Pair {
    public int first;
    public int second;
 
    public Pair(int first, int second)
    {
        this.first = first;
        this.second = second;
    }
}

                    

Python3

# function to check if there exist four
# elements whose sum is equal to k
def findfour(arr, n, k):
   
    # dictionary to store sum and indexes for
    # a pair sum
    hash = {}
 
    for i in range(n):
        for j in range(i + 1, n):
 
            # calculate the sum of each pair
            s = arr[i] + arr[j]
 
            # if k-sum exist in dictionary
            if k-s in hash:
                # check for index coincidence as if
                # there is a common that means all
                # the four numbers are not from
                # different indexes and one of the
                # index is repeated
                for pair in hash[k-s]:
                    if pair[0] != i and pair[0] != j and pair[1] != i and pair[1] != j:
                        return True
 
            # store the sum and index pair in dictionary
            if s in hash:
                hash[s].append((i, j))
            else:
                hash[s] = [(i, j)]
    return False
 
# Driver code
k = 7
arr = [1, 5, 1, 0, 6, 0]
n = len(arr)
if findfour(arr, n, k):
    print("YES")
else:
    print("NO")
 
    # This code is contributed by divya_p123.

                    

C#

using System;
using System.Collections.Generic;
 
class Gfg {
    public static bool findfour(int[] arr, int n, int k)
    {
        Dictionary<int, List<Tuple<int, int> > > hash
            = new Dictionary<int,
                             List<Tuple<int, int> > >();
 
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                // calculate the sum of each pair
                int sum = arr[i] + arr[j];
 
                // if k-sum exists in dictionary
                if (hash.ContainsKey(k - sum)) {
                    List<Tuple<int, int> > v
                        = hash[k - sum];
 
                    for (int kk = 0; kk < v.Count; kk++) {
                        Tuple<int, int> it = v[kk];
                        if (it.Item1 != i && it.Item1 != j
                            && it.Item2 != i
                            && it.Item2 != j) {
                            return true;
                        }
                    }
                }
 
                if (!hash.ContainsKey(sum)) {
                    hash.Add(sum,
                             new List<Tuple<int, int> >());
                }
                hash[sum].Add(Tuple.Create(i, j));
            }
        }
 
        hash.Clear();
        return false;
    }
 
    public static void Main(string[] args)
    {
        int k = 7;
        int[] arr = { 1, 5, 1, 0, 6, 0 };
        int n = arr.Length;
        if (findfour(arr, n, k)) {
            Console.WriteLine("YES");
        }
        else {
            Console.WriteLine("NO");
        }
    }
}
 
class Pair {
    public int first;
    public int second;
 
    public Pair(int first, int second)
    {
        this.first = first;
        this.second = second;
    }
}

                    

Javascript

// JavaScript Code implementation.
const findFour = (arr, n, k) => {
      let hash = {};
 
    for (let i = 0; i < n; i++)
    {
        for (let j = i + 1; j < n; j++)
        {
         
            // calculate the sum of each pair
            let sum = arr[i] + arr[j];
 
            // if k-sum exists in map
            if (hash[k - sum]) {
                let v = hash[k - sum];
                for (let kk = 0; kk < v.length; kk++) {
                    let it = v[kk];
                    if (it[0] !== i && it[0] !== j && it[1] !== i && it[1] !== j) {
                          return true;
                    }
                }
            }
 
            if (!hash[sum]) {
                  hash[sum] = [];
            }
            hash[sum].push([i, j]);
        }
    }
 
      hash = {};
      return false;
};
 
let k = 7;
let arr = [1, 5, 1, 0, 6, 0];
let n = arr.length;
if (findFour(arr, n, k)) {
      console.log("YES");
} else {
      console.log("NO");
}
 
// This code is contributed by lokeshmvs21.

                    

Output
YES

Time Complexity: O(n^2)
Auxiliary Space: O(n) for hashmap



Last Updated : 31 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads