Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Print elements that can be added to form a given sum
Next article icon

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

Last Updated : 31 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
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



Next Article
Print elements that can be added to form a given sum
https://media.geeksforgeeks.org/auth/avatar.png
GeeksforGeeks
Improve
Article Tags :
  • Arrays
  • DSA
  • Hash
Practice Tags :
  • Arrays
  • Hash

Similar Reads

  • Find three element from given three arrays such that their sum is X | Set 2
    Given three sorted integer arrays A[], B[] and C[], the task is to find three integers, one from each array such that they sum up to a given target value X. Print Yes or No depending on whether such triplet exists or not.Examples: Input: A[] = {2}, B[] = {1, 6, 7}, C[] = {4, 5}, X = 12 Output: Yes A
    9 min read
  • Print elements that can be added to form a given sum
    Given an array arr[] of positive integers and a sum, the task is to print the elements that will be included to get the given sum. Note: Consider the elements in the form of queue i.e. Elements to be added from starting and up to the sum of elements is lesser or becomes equal to the given sum.Also,
    5 min read
  • Find all triplets that sum to a given value or less
    Given an array, arr[] and integer X. Find all the possible triplets from an arr[] whose sum is either equal to less than X. Example: Input : arr[] = {-1, 1, 3, 2}, X = 3Output: (-1, 1, 3), (-1, 1, 2)Explanation: If checked manually, the above two are the only triplets from possible 4 triplets whose
    7 min read
  • Find sum of all unique elements in the array for K queries
    Given an arrays arr[] in which initially all elements are 0 and another array Q[][] containing K queries where every query represents a range [L, R], the task is to add 1 to each subarrays where each subarray is defined by the range [L, R], and return sum of all unique elements.Note: One-based index
    8 min read
  • Find a triplet such that sum of two equals to third element
    Given an array of integers, you have to find three numbers such that the sum of two elements equals the third element. Examples: Input: arr[] = [1, 2, 3, 4, 5]Output: TrueExplanation: The pair (1, 2) sums to 3. Input: arr[] = [3, 4, 5]Output: TrueExplanation: No triplets satisfy the condition. Input
    14 min read
  • Javascript Program to Find a triplet that sum to a given value
    Given an array and a value, find if there is a triplet in array whose sum is equal to the given value. If there is such a triplet present in array, then print the triplet and return true. Else return false. Examples: Input: array = {12, 3, 4, 1, 6, 9}, sum = 24; Output: 12, 3, 9 Explanation: There i
    6 min read
  • Count sub-sets that satisfy the given condition
    Given an array arr[] and an integer x, the task is to count the number of sub-sets of arr[] sum of all of whose sub-sets (individually) is divisible by x. Examples: Input: arr[] = {2, 4, 3, 7}, x = 2 Output: 3 All valid sub-sets are {2}, {4} and {2, 4} {2} => 2 is divisible by 2 {4} => 4 is di
    5 min read
  • Maximize 3rd element sum in quadruplet sets formed from given Array
    Given an array arr containing N values describing the priority of N jobs. The task is to form sets of quadruplets (W, X, Y, Z) to be done each day such that W >= X >= Y >= Z and in doing so, maximize the sum of all Y across all quadruplet sets. Note: N will always be a multiple of 4.Example
    7 min read
  • Count triplets with sum smaller than a given value
    Given an array of distinct integers and a sum value. Find count of triplets with sum smaller than given sum value. The expected Time Complexity is O(n2).Examples: Input : arr[] = {-2, 0, 1, 3} sum = 2. Output : 2 Explanation : Below are triplets with sum less than 2 (-2, 0, 1) and (-2, 0, 3) Input :
    11 min read
  • Find N'th item in a set formed by sum of two arrays
    Given two sorted arrays, we can get a set of sums(add one element from the first and one from second). Find the N'th element in the elements of the formed set considered in sorted order. Note: Set of sums should have unique elements. Examples: Input: arr1[] = {1, 2} arr2[] = {3, 4} N = 3 Output: 6 W
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences