Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

# Thread: Returning the equilibrium index in a sequence of integers

1. ## 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:

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=-7 A=1 A=5 A=2 A=-4 A=3 A=0
3 is an equilibrium index, because:

A+A+A=A+A+A
6 is also an equilibrium index, because:

A+A+A+A+A+A=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:

```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: 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... 3. ## Re: Returning the equilibrium index in a sequence of integers

Use big integers, or use longs. 4. ## 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.  5. ## Re: Returning the equilibrium index in a sequence of integers

...
100% 6. ## 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. 