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++
#include <bits/stdc++.h>
using namespace std;
bool checkForElement( int array[], int n)
{
int sum = 0;
for ( int i = 0; i < n; i++)
sum += array[i];
if (sum % 2)
return false ;
sum /= 2;
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 ;
}
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
import java.io.*;
class GFG {
static boolean checkForElement( int array[], int n)
{
int sum = 0 ;
for ( int i = 0 ; i < n; i++)
sum += array[i];
if (sum % 2 > 0 )
return false ;
sum /= 2 ;
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 ;
}
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" );
}
}
|
Python3
def checkForElement(array, n):
sum = 0
for i in range (n):
sum + = array[i]
if ( sum % 2 ):
return False
sum / / = 2
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
if __name__ = = "__main__" :
array = [ 1 , 2 , 3 ]
n = len (array)
if (checkForElement(array, n)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG
{
static bool checkForElement( int [] array,
int n)
{
int sum = 0;
for ( int i = 0; i < n; i++)
sum += array[i];
if (sum % 2 > 0)
return false ;
sum /= 2;
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 ;
}
static void Main()
{
int []array = { 1, 2, 3 };
int n = array.Length;
if (checkForElement(array, n))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
PHP
<?php
function checkForElement(& $array , $n )
{
$sum = 0;
for ( $i = 0; $i < $n ; $i ++)
$sum += $array [ $i ];
if ( $sum % 2)
return false;
$sum /= 2;
$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;
}
$array = array (1, 2, 3 );
$n = sizeof( $array );
if (checkForElement( $array , $n ))
echo "Yes" ;
else
echo "No" ;
?>
|
Javascript
<script>
function checkForElement(array, n)
{
let sum = 0;
for (let i = 0; i < n; i++)
sum += array[i];
if (sum % 2)
return false ;
sum = Math.floor(sum / 2);
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 ;
}
let array = new Array(1, 2, 3 );
let n = array.length;
if (checkForElement(array, n))
document.write( "Yes" );
else
document.write( "No" );
</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++
#include <bits/stdc++.h>
using namespace std;
bool checkForElement( int array[], int n)
{
unordered_set< int > s;
int sum = 0;
for ( int i = 0; i < n; i++) {
sum += array[i];
s.insert(array[i]);
}
if (sum % 2 == 0 && s.find(sum/2) != s.end())
return true ;
else
return false ;
}
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
import java.util.*;
class GFG {
static boolean checkForElement( int array[], int n) {
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 == 0 && s.contains(sum / 2 )
&& (sum / 2 )== s.stream().skip(s.size() - 1 ).findFirst().get()) {
return true ;
} else {
return false ;
}
}
public static void main(String[] args) {
int array[] = { 1 , 2 , 3 };
int n = array.length;
System.out.println(checkForElement(array, n) ? "Yes" : "No" );
}
}
|
Python3
def checkForElement(array, n):
s = set ()
sum = 0
for i in range (n):
sum + = array[i]
s.add(array[i])
f = int ( sum / 2 )
if ( sum % 2 = = 0 and f in s):
return True
else :
return False
if __name__ = = '__main__' :
array = [ 1 , 2 , 3 ]
n = len (array)
if (checkForElement(array, n)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static Boolean checkForElement( int []array, int n)
{
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 == 0 && s.Contains(sum / 2))
{
return true ;
}
else
{
return false ;
}
}
public static void Main(String[] args)
{
int []array = {1, 2, 3};
int n = array.Length;
Console.WriteLine(checkForElement(array, n) ? "Yes" : "No" );
}
}
|
Javascript
<script>
function checkForElement(array, n)
{
let s = new Set();
let sum = 0;
for (let i = 0; i < n; i++)
{
sum += array[i];
s.add(array[i]);
}
if (sum % 2 == 0 && s.has(sum / 2))
{
return true ;
}
else
{
return false ;
}
}
let array = [ 1, 2, 3 ];
let n = array.length;
document.write(
checkForElement(array, n) ? "Yes" : "No" );
</script>
|
Complexity Analysis:
- Time Complexity: O(n)
- Auxiliary Space: O(n)
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!