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:
Check if Sum and XOR of all elements of array is equal
Next article icon

Check if each element of an Array is the Sum of any two elements of another Array

Last Updated : 06 Jun, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two arrays A[] and B[] consisting of N integers, the task is to check if each element of array B[] can be formed by adding any two elements of array A[]. If it is possible, then print “Yes”. Otherwise, print “No”.

Examples:

Input: A[] = {3, 5, 1, 4, 2}, B[] = {3, 4, 5, 6, 7} 
Output: Yes 
Explanation: 
B[0] = 3 = (1 + 2) = A[2] + A[4], 
B[1] = 4 = (1 + 3) = A[2] + A[0], 
B[2] = 5 = (3 + 2) = A[0] + A[4], 
B[3] = 6 = (2 + 4) = A[4] + A[3], 
B[4] = 7 = (3 + 4) = A[0] + A[3]

Input: A[] = {1, 2, 3, 4, 5}, B[] = {1, 2, 3, 4, 5} 
Output: No 
 

Approach: 
Follow the steps below to solve the problem: 

  • Store each element of B[] in a Set.
  • For each pair of indices (i, j) of the array A[], check if A[i] + A[j] is present in the set. If found to be true, remove A[i] + A[j] from the set.
  • If the set becomes empty, then print “Yes”. Otherwise, print “No”.

Below is the implementation of the above approach: 

C++




// C++ program to implement
// the above approach
#include 
using namespace std;
 
// Function to check if each element
// of B[] can be formed by adding two
// elements of array A[]
string checkPossible(int A[], int B[], int n)
{
    // Store each element of B[]
    unordered_set values;
 
    for (int i = 0; i < n; i++) {
        values.insert(B[i]);
    }
 
    // Traverse all possible pairs of array
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
 
            // If A[i] + A[j] is present in
            // the set
            if (values.find(A[i] + A[j])
                != values.end()) {
 
                // Remove A[i] + A[j] from the set
                values.erase(A[i] + A[j]);
 
                if (values.empty())
                    break;
            }
        }
    }
 
    // If set is empty
    if (values.size() == 0)
        return "Yes";
 
    // Otherwise
    else
        return "No";
}
 
// Driver Code
int main()
{
    int N = 5;
 
    int A[] = { 3, 5, 1, 4, 2 };
    int B[] = { 3, 4, 5, 6, 7 };
 
    cout << checkPossible(A, B, N);
}
 
 

Java




// Java program to implement
// the above approach
import java.io.*;
import java.util.*;
 
class GFG{
     
// Function to check if each element
// of B[] can be formed by adding two
// elements of array A[]
static String checkPossible(int A[], int B[],
                            int n)
{
     
    // Store each element of B[]
    Set values = new HashSet();
 
    for(int i = 0; i < n; i++)
    {
        values.add(B[i]);
    }
 
    // Traverse all possible pairs of array
    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < n; j++)
        {
 
            // If A[i] + A[j] is present in
            // the set
            if (values.contains(A[i] + A[j]))
            {
                 
                // Remove A[i] + A[j] from the set
                values.remove(A[i] + A[j]);
 
                if (values.size() == 0)
                    break;
            }
        }
    }
 
    // If set is empty
    if (values.size() == 0)
        return "Yes";
 
    // Otherwise
    else
        return "No";
}
 
// Driver Code
public static void main(String args[])
{
    int N = 5;
    int A[] = { 3, 5, 1, 4, 2 };
    int B[] = { 3, 4, 5, 6, 7 };
     
    System.out.print(checkPossible(A, B, N));
}
}
 
// This code is contributed by offbeat
 
 

Python3




# Python3 program to implement
# the above approach
 
# Function to check if each element
# of B[] can be formed by adding two
# elements of array A[]
def checkPossible(A, B, n):
 
    # Store each element of B[]
    values = set([])
 
    for i in range (n):
        values.add(B[i])
     
    # Traverse all possible
    # pairs of array
    for i in range (n):
        for j in range (n):
 
            # If A[i] + A[j] is present in
            # the set
            if ((A[i] + A[j]) in values):
 
                # Remove A[i] + A[j] from the set
                values.remove(A[i] + A[j])
 
                if (len(values) == 0):
                    break
 
    # If set is empty
    if (len(values) == 0):
        return "Yes"
 
    # Otherwise
    else:
        return "No"
 
# Driver Code
if __name__ == "__main__":
   
  N = 5
 
  A = [3, 5, 1, 4, 2]
  B = [3, 4, 5, 6, 7]
 
  print (checkPossible(A, B, N))
 
# This code is contributed by Chitranayal
 
 

C#




// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
class GFG{
     
// Function to check if each element
// of []B can be formed by adding two
// elements of array []A
static String checkPossible(int []A, int []B,
                            int n)
{
 
  // Store each element of []B
  HashSet values = new HashSet();
 
  for(int i = 0; i < n; i++)
  {
    values.Add(B[i]);
  }
 
  // Traverse all possible pairs of array
  for(int i = 0; i < n; i++)
  {
    for(int j = 0; j < n; j++)
    {
      // If A[i] + A[j] is present in
      // the set
      if (values.Contains(A[i] + A[j]))
      {                
        // Remove A[i] + A[j] from the set
        values.Remove(A[i] + A[j]);
 
        if (values.Count == 0)
          break;
      }
    }
  }
 
  // If set is empty
  if (values.Count == 0)
    return "Yes";
 
  // Otherwise
  else
    return "No";
}
 
// Driver Code
public static void Main(String []args)
{
  int N = 5;
  int []A = {3, 5, 1, 4, 2};
  int []B = {3, 4, 5, 6, 7};
 
  Console.Write(checkPossible(A, B, N));
}
}
 
// This code is contributed by Amit Katiyar
 
 

Javascript




<script>
 
// Javascript program to implement
// the above approach
 
// Function to check if each element
// of B[] can be formed by adding two
// elements of array A[]
function checkPossible(A, B, n)
{
     
    // Store each element of B[]
    var values = new Set();
 
    for(var i = 0; i < n; i++)
    {
        values.add(B[i]);
    }
 
    // Traverse all possible pairs of array
    for(var i = 0; i < n; i++)
    {
        for(var j = 0; j < n; j++)
        {
             
            // If A[i] + A[j] is present in
            // the set
            if (values.has(A[i] + A[j]))
            {
                 
                // Remove A[i] + A[j] from the set
                values.delete(A[i] + A[j]);
 
                if (values.size == 0)
                    break;
            }
        }
    }
 
    // If set is empty
    if (values.size == 0)
        return "Yes";
 
    // Otherwise
    else
        return "No";
}
 
// Driver Code
var N = 5;
var A = [ 3, 5, 1, 4, 2 ];
var B = [ 3, 4, 5, 6, 7 ];
 
document.write(checkPossible(A, B, N));
 
// This code is contributed by itsok
 
</script>
 
 
Output: 
Yes

 

Time Complexity: O(N2) 
Auxiliary Space: O(N) 



Next Article
Check if Sum and XOR of all elements of array is equal
author
jrishabh99
Improve
Article Tags :
  • Arrays
  • DSA
  • Hash
  • Mathematical
  • Searching
  • cpp-set
  • HashSet
Practice Tags :
  • Arrays
  • Hash
  • Mathematical
  • Searching

Similar Reads

  • Sum of Bitwise AND of each array element with the elements of another array
    Given two arrays arr1[] of size M and arr2[] of size N, the task is to find the sum of bitwise AND of each element of arr1[] with the elements of the array arr2[]. Examples: Input: arr1[] = {1, 2, 3}, arr2[] = {1, 2, 3}, M = 3, N = 3Output: 2 4 6Explanation:For elements at index 0 in arr1[], Sum = a
    11 min read
  • Sum of Bitwise OR of each array element of an array with all elements of another array
    Given two arrays arr1[] of size M and arr2[] of size N, the task is to find the sum of bitwise OR of each element of arr1[] with every element of the array arr2[]. Examples: Input: arr1[] = {1, 2, 3}, arr2[] = {1, 2, 3}, M = 3, N = 3Output: 7 8 9Explanation: For arr[0]: Sum = arr1[0]|arr2[0] + arr1[
    11 min read
  • Form an array of distinct elements with each element as sum of an element from each array
    Given two arrays, arr1[] and arr2[] of equal size, which contain distinct elements, the task is to find another array with distinct elements such that elements of the third array are formed by the addition of the one-one element of the arr1[] and arr2[]. Examples: Input: arr[] = {1, 7, 8, 3}, arr2[]
    6 min read
  • Check if an array is subset of another array
    Given two arrays a[] and b[] of size m and n respectively, the task is to determine whether b[] is a subset of a[]. Both arrays are not sorted, and elements are distinct. Examples: Input: a[] = [11, 1, 13, 21, 3, 7], b[] = [11, 3, 7, 1] Output: true Input: a[]= [1, 2, 3, 4, 5, 6], b = [1, 2, 4] Outp
    13 min read
  • Check if Sum and XOR of all elements of array is equal
    Given an array arr[], the task is to check if sum of all elements of an array is equal to XOR of all elements of array. Example: Input: arr[] = [1, 2] Output: YES Explanation: Sum = (1+2) = 3 XOR = (1^2) = 3 Input: arr[] = [6, 3, 7, 10] Output: NO Explanation: Sum = (6 + 3 + 7 + 10) = 26 XOR = (6 ^
    4 min read
  • Find an element in array such that sum of left array is equal to sum of right array
    Given, an array of size n. Find an element that divides the array into two sub-arrays with equal sums. Examples: Input: 1 4 2 5 0Output: 2Explanation: If 2 is the partition, subarrays are : [1, 4] and [5] Input: 2 3 4 1 4 5Output: 1Explanation: If 1 is the partition, Subarrays are : [2, 3, 4] and [4
    15+ min read
  • Check if the sum of K least and most frequent array elements are equal or not
    Given an array arr[] consisting of N integers, the task is to check if the sum of K most frequent array elements and the sum of K least frequent array elements in the array arr[] are equal or not. If found to be true, then print Yes. Otherwise, print No. Examples: Input: arr[] = { 3, 2, 1, 2, 3, 3,
    10 min read
  • Check if the array has an element which is equal to sum of all the remaining elements
    Given an array of N elements, the task is to check if the array has an element that is equal to the sum of all the remaining elements. Examples: Input: a[] = {5, 1, 2, 2} Output: Yes we can write 5=(1+2+2) Input: a[] = {2, 1, 2, 4, 3} Output: No Approach: Suppose that the total elements in the array
    10 min read
  • For each element in 1st array count elements less than or equal to it in 2nd array | Set 2
    Given two unsorted arrays arr1[] and arr2[]. They may contain duplicates. For each element in arr1[] count elements less than or equal to it in array arr2[]. Examples: Input : arr1[] = [1, 2, 3, 4, 7, 9] arr2[] = [0, 1, 2, 1, 1, 4] Output : [4, 5, 5, 6, 6, 6] Explanation: There are 4 elements less t
    13 min read
  • Modify array to another given array by replacing array elements with the sum of the array
    Given an array input[] consisting only of 1s initially and an array target[] of size N, the task is to check if the array input[] can be converted to target[] by replacing input[i] with the sum of array elements in each step. If found to be true, then print "YES". Otherwise, print "NO". Examples: In
    13 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