Given an array a[] of positive integers of size N. The task is to remove one element from the given array such that the arithmetic mean of the array remains the same as it was before. If it is possible to remove any such number then print that number. Otherwise, print -1.
Examples:
Input : a[] = {1, 2, 3, 4, 5}
Output : 3
Mean of the given array is 3. After removing the 3rd element
array becomes {1, 2, 4, 5} whose mean is 3 too.
Input : a[] = {5, 4, 3, 6}
Output : -1
Approach :
An efficient approach is to find the mean of the array, and check whether the mean is present in the given array or not. We can only remove elements whose value is equal to mean.
let mean of the original array be M, the sum of the elements be sum. Then sum = M * N. After removing M, the new mean will be ( (M * N ) – M) / (N – 1) = M, which remains same. So just use any search approach and print the element.
Below is the implementation of the above approach :
C++
#include <bits/stdc++.h>
using namespace std;
int FindElement( int a[], int n)
{
int sum = 0;
for ( int i = 0; i < n; i++)
sum = sum + a[i];
if (sum % n == 0) {
int m = sum / n;
for ( int i = 0; i < n; i++)
if (a[i] == m)
return m;
}
return -1;
}
int main()
{
int a[] = { 1, 2, 3, 4, 5 };
int n = sizeof (a) / sizeof ( int );
cout << FindElement(a, n);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int FindElement( int a[], int n)
{
int sum = 0 ;
for ( int i = 0 ; i < n; i++)
sum = sum + a[i];
if (sum % n == 0 )
{
int m = sum / n;
for ( int i = 0 ; i < n; i++)
if (a[i] == m)
return m;
}
return - 1 ;
}
public static void main (String[] args)
{
int a[] = { 1 , 2 , 3 , 4 , 5 };
int n = a.length;
System.out.print(FindElement(a, n));
}
}
|
Python3
def FindElement(a, n):
s = 0
for i in range (n):
s = s + a[i]
if s % n = = 0 :
m = s / / n
for j in range (n):
if a[j] = = m:
return m
return - 1
if __name__ = = "__main__" :
a = [ 1 , 2 , 3 , 4 , 5 ]
n = len (a)
print (FindElement(a, n))
|
C#
using System;
class GFG
{
static int FindElement( int []a, int n)
{
int sum = 0;
for ( int i = 0; i < n; i++)
sum = sum + a[i];
if (sum % n == 0)
{
int m = sum / n;
for ( int i = 0; i < n; i++)
if (a[i] == m)
return m;
}
return -1;
}
public static void Main ()
{
int []a = { 1, 2, 3, 4, 5 };
int n = a.Length;
Console.WriteLine(FindElement(a, n));
}
}
|
Javascript
<script>
function FindElement(a, n)
{
let sum = 0;
for (let i = 0; i < n; i++)
sum = sum + a[i];
if (sum % n == 0) {
let m = parseInt(sum / n);
for (let i = 0; i < n; i++)
if (a[i] == m)
return m;
}
return -1;
}
let a = [ 1, 2, 3, 4, 5 ];
let n = a.length;
document.write(FindElement(a, n));
</script>
|
Output:
3
Time Complexity : O(N)
Auxiliary Space: O(1)
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 geeks!