# Returning the equilibrium index in a sequence of integers

• October 13th, 2010, 12:04 PM
thanasisk
Returning the equilibrium index in a sequence of integers
Hi guys.

I'm new to the forum. I was playing with an online Java test from codility about a function that returns the equilibrium index in a sequence of integers (Codility). The problem states:

Quote:

Equilibrium index of a sequence is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes. For example, in a sequence A:

A[0]=-7 A[1]=1 A[2]=5 A[3]=2 A[4]=-4 A[5]=3 A[6]=0
3 is an equilibrium index, because:

A[0]+A[1]+A[2]=A[4]+A[5]+A[6]
6 is also an equilibrium index, because:

A[0]+A[1]+A[2]+A[3]+A[4]+A[5]=0
(sum of zero elements is zero) 7 is not an equilibrium index, because it is not a valid index of sequence A.

[...]

Assume the sum of zero elements is equal zero. Write a function
int equi(int[] A);
that given a sequence, returns its equilibrium index (any) or -1 if no equilibrium indexes exist. Assume that the sequence may be very long.
My solution to this was the following:

Code :

```int equi ( int[] A ) {   int leftSum = 0; int rightSum = 0;   for (int iterator= 0; iterator< A.length; iterator++){ rightSum += A[iterator]; }   for(int eqIndexCandidate = 0; eqIndexCandidate < A.length; eqIndexCandidate ++){   if (eqIndexCandidate != 0) leftSum += A[eqIndexCandidate - 1];   rightSum -= A[eqIndexCandidate];   if (leftSum == rightSum) return eqIndexCandidate;   }   return -1; }```

However, when I got the results back it seems that I missed one case:

http://img837.imageshack.us/img837/3...ityresults.png

How would you deal with a case that the numbers are too large to fit in an integer ? It seems that Codility would not let me use any packages from the API...
• October 13th, 2010, 03:23 PM
helloworld922
Re: Returning the equilibrium index in a sequence of integers
Use big integers, or use longs.
• November 20th, 2010, 06:01 AM
sanjeev2205
Re: Returning the equilibrium index in a sequence of integers
large numbers - check for Integer.MAX_VALUE and MIN_VALUE before summing the stuff. I got 100% there.:)
• September 3rd, 2013, 12:26 PM
opastukhov
Re: Returning the equilibrium index in a sequence of integers
...
100%
• September 3rd, 2013, 02:20 PM
copeg
Re: Returning the equilibrium index in a sequence of integers
@opastukhov, please don't spoonfeed, especially on a post that is almost 3 years old.