Element equal to the sum of all the remaining elements
Last Updated :
09 Sep, 2022
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}
Output: -1
Approach: First of all, find the sum of all elements of an array. Then iterate over each element and check the condition that if (a[i] == sum-a[i] ). If true then print that a[i], else print “-1” if no such element is found.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
#define ll long long int
using namespace std;
int findEle( int arr[], int n)
{
ll sum = 0;
for ( int i = 0; i < n; i++)
sum += arr[i];
for ( int i = 0; i < n; i++)
if (arr[i] == sum - arr[i])
return arr[i];
return -1;
}
int main()
{
int arr[] = { 1, 2, 3, 6 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << findEle(arr, n);
return 0;
}
|
Java
import java.io.*;
class GFG {
static int findEle( int arr[], int n)
{
int sum = 0 ;
for ( int i = 0 ; i < n; i++)
sum += arr[i];
for ( int i = 0 ; i < n; i++)
if (arr[i] == sum - arr[i])
return arr[i];
return - 1 ;
}
public static void main (String[] args) {
int arr[] = { 1 , 2 , 3 , 6 };
int n = arr.length;
System.out.print(findEle(arr, n));
}
}
|
Python3
def findEle(arr, n) :
sum = 0
for i in range (n) :
sum + = arr[i]
for i in range (n) :
if arr[i] = = sum - arr[i] :
return arr[i]
return - 1
if __name__ = = "__main__" :
arr = [ 1 , 2 , 3 , 6 ]
n = len (arr)
print (findEle(arr, n))
|
C#
using System;
class GFG
{
static int findEle( int []arr, int n)
{
int sum = 0;
for ( int i = 0; i < n; i++)
sum += arr[i];
for ( int i = 0; i < n; i++)
if (arr[i] == sum - arr[i])
return arr[i];
return -1;
}
static public void Main (String []args)
{
int []arr = { 1, 2, 3, 6 };
int n = arr.Length;
Console.WriteLine(findEle(arr, n));
}
}
|
PHP
<?php
function findEle( $arr , $n )
{
$sum = 0;
for ( $i = 0; $i < $n ; $i ++)
$sum += $arr [ $i ];
for ( $i = 0; $i < $n ; $i ++)
if ( $arr [ $i ] == $sum - $arr [ $i ])
return $arr [ $i ];
return -1;
}
$arr = array (1, 2, 3, 6 );
$n = sizeof( $arr );
echo findEle( $arr , $n );
?>
|
Javascript
<script>
function findEle(arr, n)
{
var sum = 0;
for ( var i = 0; i < n; i++)
sum += arr[i];
for ( var i = 0; i < n; i++)
if (arr[i] == sum - arr[i])
return arr[i];
return -1;
}
var arr = [1, 2, 3, 6];
var n = arr.length;
document.write(findEle(arr, n));
</script>
|
Complexity Analysis:
- Time Complexity: O(n)
- Auxiliary Space: O(1)
Note: Above problem can be solved with the concept used in Check if the array has an element which is equal to sum of all the remaining elements.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...