Find if array has an element whose value is half of array sum
Last Updated :
09 Sep, 2022
Given a sorted array (with unique entries), we have to find whether there exists an element(say X) that is exactly half the sum of all the elements of the array including X.
Examples:
Input : A = {1, 2, 3}
Output : YES
Sum of all the elements is 6 = 3*2;
Input : A = {2, 4}
Output : NO
Sum of all the elements is 6, and 3 is not present in the array.
- Calculate the sum of all the elements of the array.
- There can be two cases
- Sum is Odd, implies we cannot find such X, since all entries are integer.
- Sum is Even, if half the value of sum exist in array then answer is YES else NO.
- We can use Binary Search to find if sum/2 exist in array or not (Since it does not have duplicate entries)
Below is the implementation of above approach:
C++
// CPP program to check if array has an
// element whose value is half of array
// sum.
#include <bits/stdc++.h>
using namespace std;
// Function to check if answer exists
bool checkForElement(int array[], int n)
{
// Sum of all array elements
int sum = 0;
for (int i = 0; i < n; i++)
sum += array[i];
// If sum is odd
if (sum % 2)
return false;
sum /= 2; // If sum is Even
// Do binary search for the required element
int start = 0;
int end = n - 1;
while (start <= end)
{
int mid = start + (end - start) / 2;
if (array[mid] == sum)
return true;
else if (array[mid] > sum)
end = mid - 1;
else
start = mid + 1;
}
return false;
}
// Driver code
int main()
{
int array[] = { 1, 2, 3 };
int n = sizeof(array) / sizeof(array[0]);
if (checkForElement(array, n))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
// Java program to check if array has an
// element whose value is half of array
// sum.
import java.io.*;
class GFG {
// Function to check if answer exists
static boolean checkForElement(int array[], int n)
{
// Sum of all array elements
int sum = 0;
for (int i = 0; i < n; i++)
sum += array[i];
// If sum is odd
if (sum % 2>0)
return false;
sum /= 2; // If sum is Even
// Do binary search for the required element
int start = 0;
int end = n - 1;
while (start <= end)
{
int mid = start + (end - start) / 2;
if (array[mid] == sum)
return true;
else if (array[mid] > sum)
end = mid - 1;
else
start = mid + 1;
}
return false;
}
// Driver code
public static void main (String[] args) {
int array[] = { 1, 2, 3 };
int n = array.length;
if (checkForElement(array, n))
System.out.println( "Yes");
else
System.out.println( "No");
}
}
// This code is contributed by anuj_67..
Python3
# Python 3 program to check if array
# has an element whose value is half
# of array sum.
# Function to check if answer exists
def checkForElement(array, n):
# Sum of all array elements
sum = 0
for i in range(n):
sum += array[i]
# If sum is odd
if (sum % 2):
return False
sum //= 2 # If sum is Even
# Do binary search for the
# required element
start = 0
end = n - 1
while (start <= end) :
mid = start + (end - start) // 2
if (array[mid] == sum):
return True
elif (array[mid] > sum) :
end = mid - 1;
else:
start = mid + 1
return False
# Driver code
if __name__ == "__main__":
array = [ 1, 2, 3 ]
n = len(array)
if (checkForElement(array, n)):
print("Yes")
else:
print("No")
# This code is contributed
# by ChitraNayal
C#
// C# program to check if array has
// an element whose value is half
// of array sum.
using System;
class GFG
{
// Function to check if answer exists
static bool checkForElement(int[] array,
int n)
{
// Sum of all array elements
int sum = 0;
for (int i = 0; i < n; i++)
sum += array[i];
// If sum is odd
if (sum % 2 > 0)
return false;
sum /= 2; // If sum is Even
// Do binary search for the
// required element
int start = 0;
int end = n - 1;
while (start <= end)
{
int mid = start + (end - start) / 2;
if (array[mid] == sum)
return true;
else if (array[mid] > sum)
end = mid - 1;
else
start = mid + 1;
}
return false;
}
// Driver Code
static void Main()
{
int []array = { 1, 2, 3 };
int n = array.Length;
if (checkForElement(array, n))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by ANKITRAI1
PHP
<?php
// PHP program to check if array has an
// element whose value is half of array
// sum.
// Function to check if answer exists
function checkForElement(&$array, $n)
{
// Sum of all array elements
$sum = 0;
for ($i = 0; $i < $n; $i++)
$sum += $array[$i];
// If sum is odd
if ($sum % 2)
return false;
$sum /= 2; // If sum is Even
// Do binary search for the
// required element
$start = 0;
$end = $n - 1;
while ($start <= $end)
{
$mid = $start + ($end - $start) / 2;
if ($array[$mid] == $sum)
return true;
else if ($array[$mid] > $sum)
$end = $mid - 1;
else
$start = $mid + 1;
}
return false;
}
// Driver code
$array = array(1, 2, 3 );
$n = sizeof($array);
if (checkForElement($array, $n))
echo "Yes";
else
echo "No";
// This code is contributed
// by Shivi_Aggarwal
?>
JavaScript
<script>
// Javascript program to check if array has an
// element whose value is half of array
// sum.
// Function to check if answer exists
function checkForElement(array, n)
{
// Sum of all array elements
let sum = 0;
for (let i = 0; i < n; i++)
sum += array[i];
// If sum is odd
if (sum % 2)
return false;
sum = Math.floor(sum / 2); // If sum is Even
// Do binary search for the
// required element
let start = 0;
let end = n - 1;
while (start <= end)
{
let mid = Math.floor(start + (end - start) / 2);
if (array[mid] == sum)
return true;
else if (array[mid] > sum)
end = mid - 1;
else
start = mid + 1;
}
return false;
}
// Driver code
let array = new Array(1, 2, 3 );
let n = array.length;
if (checkForElement(array, n))
document.write("Yes");
else
document.write("No");
// This code is contributed by _saurabh_jaiswal
</script>
Complexity Analysis:
- Time Complexity: O(n)
- Auxiliary Space: O(1)
Another efficient solution that works for unsorted arrays also
Implementation: The idea is to use hashing.
C++
// CPP program to check if array has an
// element whose value is half of array
// sum.
#include <bits/stdc++.h>
using namespace std;
// Function to check if answer exists
bool checkForElement(int array[], int n)
{
// Sum of all array elements
// and storing in a hash table
unordered_set<int> s;
int sum = 0;
for (int i = 0; i < n; i++) {
sum += array[i];
s.insert(array[i]);
}
// If sum/2 is present in hash table
if (sum % 2 == 0 && s.find(sum/2) != s.end())
return true;
else
return false;
}
// Driver code
int main()
{
int array[] = { 1, 2, 3 };
int n = sizeof(array) / sizeof(array[0]);
if (checkForElement(array, n))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
// Java program to check if array has an
// element whose value is half of array
// sum.
import java.util.*;
class GFG {
// Function to check if answer exists
static boolean checkForElement(int array[], int n) {
// Sum of all array elements
// and storing in a hash table
Set<Integer> s = new LinkedHashSet<>();
int sum = 0;
for (int i = 0; i < n; i++) {
sum += array[i];
s.add(array[i]);
}
// If sum/2 is present in hash table
if (sum % 2 == 0 && s.contains(sum / 2)
&& (sum / 2 )== s.stream().skip(s.size() - 1).findFirst().get()) {
return true;
} else {
return false;
}
}
// Driver code
public static void main(String[] args) {
int array[] = {1, 2, 3};
int n = array.length;
System.out.println(checkForElement(array, n) ? "Yes" : "No");
}
}
// This code is contributed by 29AjayKumar
Python3
# Python 3 program to check if array has an
# element whose value is half of array
# sum.
# Function to check if answer exists
def checkForElement(array, n):
# Sum of all array elements
# and storing in a hash table
s = set()
sum = 0
for i in range(n):
sum += array[i]
s.add(array[i])
# If sum/2 is present in hash table
f = int(sum / 2)
if (sum % 2 == 0 and f in s):
return True
else:
return False
# Driver code
if __name__ == '__main__':
array = [1, 2, 3]
n = len(array)
if (checkForElement(array, n)):
print("Yes")
else:
print("No")
# This code is contributed by
# Surendra_Gangwar
C#
// C# program to check if array has an
// element whose value is half of array
// sum.
using System;
using System.Collections.Generic;
class GFG
{
// Function to check if answer exists
static Boolean checkForElement(int []array, int n)
{
// Sum of all array elements
// and storing in a hash table
HashSet<int> s = new HashSet<int>();
int sum = 0;
for (int i = 0; i < n; i++)
{
sum += array[i];
s.Add(array[i]);
}
// If sum/2 is present in hash table
if (sum % 2 == 0 && s.Contains(sum / 2))
{
return true;
}
else
{
return false;
}
}
// Driver code
public static void Main(String[] args)
{
int []array = {1, 2, 3};
int n = array.Length;
Console.WriteLine(checkForElement(array, n) ? "Yes" : "No");
}
}
// This code is contributed by Princi Singh
JavaScript
<script>
// Javascript program to check if array has an
// element whose value is half of array
// sum.
// Function to check if answer exists
function checkForElement(array, n)
{
// Sum of all array elements
// and storing in a hash table
let s = new Set();
let sum = 0;
for(let i = 0; i < n; i++)
{
sum += array[i];
s.add(array[i]);
}
// If sum/2 is present in hash table
if (sum % 2 == 0 && s.has(sum / 2))
{
return true;
}
else
{
return false;
}
}
// Driver code
let array = [ 1, 2, 3 ];
let n = array.length;
document.write(
checkForElement(array, n) ? "Yes" : "No");
// This code is contributed by rag2127
</script>
Complexity Analysis:
- Time Complexity: O(n)
- Auxiliary Space: O(n)
Similar Reads
Find the sum of the first half and second half elements of an array Given an array arr of size N. The task is to find the sum of the first half (N/2) elements and the second half elements (N - N/2) of an array. Examples: Input : arr[] = {20, 30, 60, 10, 25, 15, 40}Â Output : 110, 90Â Sum of first N/2 elements 20 + 30 + 60 is 110Input : arr[] = {50, 35, 20, 15}Â Outp
10 min read
Find pairs in array whose sums already exist in array Given an array of n distinct and positive elements, the task is to find pair whose sum already exists in the given array. Examples : Input : arr[] = {2, 8, 7, 1, 5};Output : 2 5 7 1 Input : arr[] = {7, 8, 5, 9, 11};Output : Not ExistA Naive Approach is to run three loops to find pair whose sum exist
9 min read
Find all indices of Array having value same as average of other elements Given an array arr[] of N integers, the task is to find all indices in the array, such that for each index i the arithmetic mean of all elements except arr[i] is equal to the value of the element at that index. Examples : Input: N = 5, arr[] = {1, 2, 3, 4, 5}Output : {2}Explanation : Upon removing a
6 min read
Find original Array from given Array where each element is sum of prefix and postfix sum Given an array arr[] of length N, where arr is derived from an array nums[] which is lost. Array arr[] is derived as: arr[i] = (nums[0] + nums[1] + ... + nums[i]) + (nums[i] + nums[i+1] + ... + nums[N-1]). The task is to find nums[] array of length N. Examples: Input: N = 4, arr[] = {9, 10, 11, 10}O
10 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
Find array elements equal to sum of any subarray of at least size 2 Given an array arr[], the task is to find the elements from the array which are equal to the sum of any sub-array of size greater than 1.Examples: Input: arr[] = {1, 2, 3, 4, 5, 6} Output: 3, 5, 6 Explanation: The elements 3, 5, 6 are equal to sum of subarrays {1, 2},{2, 3} and {1, 2, 3} respectivel
6 min read