Equilibrium index of an array
PROBLEM :
Equilibrium index of an array is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes . Now Given an array your task is to complete the function findEquilibrium which returns the index of the first Equilibrium point in the array. The function takes two arguments. The first argument is the array A[ ] and the second argument is the size of the array A.
Input:
The first line of input takes an integer T denoting the no of test cases, then T test cases follow. The first line of each test case is an integer N denoting The size of the array . Then in the next line are N space separated values of the array.
Output:
For each test case output will be the equilibrium index of the array .If no such index exist output will be -1.
Constraints:
1<=T<=100
1<=N<=100
-100<=A[]<=100
Example(To be used only for expected output):
Input
2
4
1 2 0 3
4
1 1 1 1
Output
2
-1
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
/* You are required to complete this method*/
int findEquilibrium(int arr[], int n)
{
int i,sum,curr ;
sum=0 ;
curr=0 ;
for(i=0;i<n;i++)
sum=sum+arr[i] ;
for(i=0;i<n;i++)
{
if(curr==sum-arr[i])
return i ;
sum=sum-arr[i] ;
curr=curr+arr[i] ;
}
return -1 ;
}
---------------------------------------------------------------------------------
Equilibrium index of an array is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes . Now Given an array your task is to complete the function findEquilibrium which returns the index of the first Equilibrium point in the array. The function takes two arguments. The first argument is the array A[ ] and the second argument is the size of the array A.
Input:
The first line of input takes an integer T denoting the no of test cases, then T test cases follow. The first line of each test case is an integer N denoting The size of the array . Then in the next line are N space separated values of the array.
Output:
For each test case output will be the equilibrium index of the array .If no such index exist output will be -1.
Constraints:
1<=T<=100
1<=N<=100
-100<=A[]<=100
Example(To be used only for expected output):
Input
2
4
1 2 0 3
4
1 1 1 1
Output
2
-1
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
/* You are required to complete this method*/
int findEquilibrium(int arr[], int n)
{
int i,sum,curr ;
sum=0 ;
curr=0 ;
for(i=0;i<n;i++)
sum=sum+arr[i] ;
for(i=0;i<n;i++)
{
if(curr==sum-arr[i])
return i ;
sum=sum-arr[i] ;
curr=curr+arr[i] ;
}
return -1 ;
}
---------------------------------------------------------------------------------
Comments
Post a Comment