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 the array has an element which is equal to sum of all the remaining elements

Last Updated : 13 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 is N. Now, if there exists any such element such that the element is equal to the sum of remaining elements then it can be said that the array can be divided into two halves with equal sum such that one half has only one element with value sum/2.

Also, since both halves have equal sum, the overall sum of the array must be even as we know that: 

  • ODD + ODD = EVEN
  • EVEN + EVEN = EVEN

Algorithm: 

  • Iterate over the array, and count the occurrence of all the elements and store in a map. Also summate the array elements.
  • The condition given in the problem is only possible when the below conditions are met. 
    1. Total Sum of the array is even
    2. sum/2 occurrence in the array should be equal to atleast 1.
  • If the above conditions are not met, hence it is not possible to remove any such element.

Below is the implementation of the above approach: 

C++
// C++ program to Check if the array // has an element which is equal to sum // of all the remaining elements  #include <bits/stdc++.h> using namespace std;  // Function to check if such element exists or not bool isExists(int a[], int n) {     // Storing frequency in map     unordered_map<int, int> freq;      // Stores the sum     int sum = 0;      // Traverse the array and count the     // array elements     for (int i = 0; i < n; i++) {         freq[a[i]]++;         sum += a[i];     }      // Only possible if sum is even     if (sum % 2 == 0) {         // If half sum is available         if (freq[sum / 2])             return true;     }      return false; }  // Driver code int main() {     int a[] = { 5, 1, 2, 2 };      int n = sizeof(a) / sizeof(a[0]);      if (isExists(a, n))         cout << "Yes";     else         cout << "No";      return 0; } 
Java
// Java program to Check if the array  // has an element which is equal to sum  // of all the remaining elements  import java.util.*; class Solution{  // Function to check if such element exists or not  static boolean isExists(int a[], int n)  {      // Storing frequency in map      Map<Integer, Integer> freq= new HashMap<Integer, Integer>();         // Stores the sum      int sum = 0;         // Traverse the array and count the      // array elements      for (int i = 0; i < n; i++) {          freq.put(a[i],freq.get(a[i])==null?0:freq.get(a[i])+1);          sum += a[i];      }         // Only possible if sum is even      if (sum % 2 == 0) {          // If half sum is available          if (freq.get(sum / 2)!=null)              return true;      }         return false;  }     // Driver code  public static void main(String args[]) {      int a[] = { 5, 1, 2, 2 };         int n = a.length;         if (isExists(a, n))          System.out.println( "Yes");      else         System.out.println( "No");     }  } //contributed by Arnab Kundu 
Python3
# Python3 code to check if the array has  # an element which is equal to sum of all  # the remaining elements  # function to check if such element # exists or not def isExists(a, n):          # storing frequency in dict     freq = {i : 0 for i in a}          #stores the sum     Sum = 0          # traverse the array and count     # the array element     for i in range(n):         freq[a[i]] += 1         Sum += a[i]          # Only possible if sum is even      if Sum % 2 == 0:                  #if half sum is available         if freq[Sum // 2]:             return True     return False      # Driver code a = [5, 1, 2, 2]  n = len(a)  if isExists(a, n):     print("Yes") else:     print("No")  # This code is contributed  # by Mohit Kumar 
C#
// C# program to Check if the array  // has an element which is equal to sum  // of all the remaining elements  using System; using System.Collections.Generic;       class Solution {  // Function to check if such element exists or not  static Boolean isExists(int []arr, int n)  {      // Storing frequency in map      Dictionary<int, int> m = new Dictionary<int, int>();           // Stores the sum      int sum = 0;           // Traverse the array and count the      // array elements      for (int i = 0; i < n; i++)      {          if(m.ContainsKey(arr[i]))         {             var val = m[arr[i]];             m.Remove(arr[i]);             m.Add(arr[i], val + 1);          }         else         {             m.Add(arr[i], 1);         }         sum += arr[i];      }           // Only possible if sum is even      if (sum % 2 == 0)      {          // If half sum is available          if (m[sum / 2] != 0)              return true;      }           return false;  }       // Driver code  public static void Main() {      int []a = { 5, 1, 2, 2 };           int n = a.Length;           if (isExists(a, n))          Console.WriteLine( "Yes");      else         Console.WriteLine( "No");  }  }  /* This code contributed by PrinciRaj1992 */ 
JavaScript
<script>  // JavaScript program to Check if the array  // has an element which is equal to sum  // of all the remaining elements   // Function to check if such element exists or not  function isExists(a, n)  {      // Storing frequency in map      let freq= new Map();         // Stores the sum      let sum = 0;         // Traverse the array and count the      // array elements      for (let i = 0; i < n; i++) {          freq.set(a[i],freq.get(a[i])==null?0:freq.get(a[i])+1);          sum += a[i];      }         // Only possible if sum is even      if (sum % 2 == 0) {          // If half sum is available          if (freq.get(sum / 2)!=null)              return true;      }         return false;  }       // Driver Code             let a = [ 5, 1, 2, 2 ];         let n = a.length;         if (isExists(a, n))          document.write( "Yes");      else         document.write( "No");           </script> 

Output
Yes

Complexity Analysis:

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

Another Approach: Calculate the total sum of all the elements in the array. Then run a FOR-loop to check if each element * 2 == total. If any such element is found, return True, else False at the end of the loop. 

  • Traverse the array and calculate the total sum of array elements
  • Check if the array has an element that is equal to the sum of all the remaining elements.
    • If true, return true,
  • Return false.

Below is the implementation of the above approach:

C++
// C++ program to Check if the array // has an element which is equal to sum // of all the remaining elements  #include <bits/stdc++.h> using namespace std;  // Function to check if such element exists or not bool isExists(int arr[], int n) {     // Stores the sum     int sum = 0;      // Traverse the array and calculate the sum     // of array elements     for (int i = 0; i < n; i++) {         sum += arr[i];     }      // Check if the array has an element that is equal to     // the sum of all the remaining elements.     for (int i = 0; i < n; i++) {         if (sum - arr[i] == arr[i])             return true;     }      return false; }  // Driver code int main() {     int a[] = { 5, 1, 2, 2 };      int n = sizeof(a) / sizeof(a[0]);      if (isExists(a, n))         cout << "Yes";     else         cout << "No";      return 0; } 
Java
// Java program to Check if the array // has an element which is equal to sum // of all the remaining elements  import java.util.*;  public class GFG {      // Function to check if such element exists or not     static boolean isExists(int arr[], int n)     {         // Stores the sum         int sum = 0;          // Traverse the array and calculate the sum         // of array elements         for (int i = 0; i < n; i++) {             sum += arr[i];         }          // Check if the array has an element that is equal         // to the sum of all the remaining elements.         for (int i = 0; i < n; i++) {             if (sum - arr[i] == arr[i])                 return true;         }          return false;     }      // Driver code     public static void main(String[] args)     {         int a[] = { 5, 1, 2, 2 };          int n = a.length;          if (isExists(a, n))             System.out.println("Yes");         else             System.out.println("No");     } }  // This code is contributed by Karandeep1234 
Python3
# Python program to Check if the array # has an element which is equal to sum # of all the remaining elements  # Function to check if such element exists or not def isExists(arr, n):     # Stores the sum     sum = 0      # Traverse the array and calculate the sum     # of array elements     for i in range(n):         sum += arr[i]      # Check if the array has an element that is equal to     # the sum of all the remaining elements.     for i in range(n):         if sum-arr[i] == arr[i]: return True      return False  # Driver code a = [5, 1, 2, 2] n = len(a) if isExists(a,n): print('Yes') else: print('No')  # This code is contributed by hardikkushwaha. 
C#
// C# program to Check if the array // has an element which is equal to sum // of all the remaining elements  using System;  public class GFG {      // Function to check if such element exists or not     static bool isExists(int[] arr, int n)     {         // Stores the sum         int sum = 0;          // Traverse the array and calculate the sum         // of array elements         for (int i = 0; i < n; i++) {             sum += arr[i];         }          // Check if the array has an element that is equal         // to the sum of all the remaining elements.         for (int i = 0; i < n; i++) {             if (sum - arr[i] == arr[i])                 return true;         }          return false;     }      // Driver code     public static void Main(string[] args)     {         int[] a = { 5, 1, 2, 2 };          int n = a.Length;          if (isExists(a, n))             Console.WriteLine("Yes");         else             Console.WriteLine("No");     } }  // This code is contributed by Karandeep1234 
JavaScript
// Javascript program to Check if the array // has an element which is equal to sum // of all the remaining elements  // Function to check if such element exists or not function isExists(arr, n) {     // Stores the sum     let sum = 0;      // Traverse the array and calculate the sum     // of array elements     for (let i = 0; i < n; i++) {         sum += arr[i];     }      // Check if the array has an element that is equal to     // the sum of all the remaining elements.     for (let i = 0; i < n; i++) {         if (sum - arr[i] == arr[i])             return true;     }      return false; }  // Driver code let a = [ 5, 1, 2, 2 ]; let n = a.length;  if (isExists(a, n))     console.log("Yes"); else     console.log("No");  // This code is contributed by poojaagarwals. 

Output
Yes

Time Complexity: O(N), where N is the length of the given array.
Auxiliary Space: O(1)


Next Article
Check if Sum and XOR of all elements of array is equal

S

Striver
Improve
Article Tags :
  • Mathematical
  • Hash
  • Competitive Programming
  • DSA
  • Arrays
  • cpp-unordered_map
Practice Tags :
  • Arrays
  • Hash
  • Mathematical

Similar Reads

  • Element equal to the sum of all the remaining elements
    Given an array of N positive elements. The task is to find an element which is equal to the sum of all elements of array except itself. Examples: Input: arr[] = {1, 2, 3, 6} Output: 6 6 is the element which is equal to the sum of all remaining elements i.e. 1 + 2+ 3 = 6 Input: arr[] = {2, 2, 2, 2} O
    4 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
  • Sum of elements in an array with frequencies greater than or equal to that element
    Given an array arr[] of N integers. The task is to find the sum of the elements which have frequencies greater than or equal to that element in the array. Examples: Input: arr[] = {2, 1, 1, 2, 1, 6} Output: 3 The elements in the array are {2, 1, 6} Where, 2 appear 2 times which is greater than equal
    9 min read
  • Find elements in given Array that are a factor of sum of remaining elements
    Given an array A[] of size N, the task is to find the elements in the array which are factors of the sum of the remaining element. So just select an element from an array and take the sum of the remaining elements and check whether the sum is perfectly divisible by the selected element or not. If it
    11 min read
  • Count of elements which is the sum of a subarray of the given Array
    Given an array arr[], the task is to count elements in an array such that there exists a subarray whose sum is equal to this element.Note: Length of subarray must be greater than 1. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7} Output: 4 Explanation: There are 4 such elements in array - arr[2] = 3
    7 min read
  • Sum of array elements excluding the elements which lie between a and b
    Given an array of N unique numbers. Also given two numbers a and b such that a will always be before b in the array. The task is to find the sum of the array elements excluding the elements which lie between a and b. Examples: Input : arr = [2, 1, 6, 9, 11], a = 6, b = 9 Output : 14 Input : arr = [1
    5 min read
  • Ways to make sum of odd and even indexed elements equal by removing an array element
    Given an array, arr[] of size n, the task is to find the count of array indices such that removing an element from these indices makes the sum of even-indexed and odd-indexed array elements equal. Examples: Input: arr[] = [ 2, 1, 6, 4 ] Output: 1 Explanation: Removing arr[1] from the array modifies
    10 min read
  • Construct an Array of size N in which sum of odd elements is equal to sum of even elements
    Given an integer N which is always even, the task is to create an array of size N which contains N/2 even numbers and N/2 odd numbers. All the elements of array should be distinct and the sum of even numbers is equal to the sum of odd numbers. If no such array exists then print -1.Examples: Input: N
    7 min read
  • Check if each element of an Array is the Sum of any two elements of another Array
    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 Explan
    6 min read
  • Make all elements of an array equal with the given operation
    Given an array arr[] of n integers and an integer k. The task is to make all the elements of arr[] equal with the given operation. In a single operation, any non-negative number x ? k (can be a floating point value) can be added to any element of the array and k will be updated as k = k - x. Print Y
    5 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