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
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read