One of the demo challenges at Codility.com is the Equilibrium Index problem. Since I noticed in the solution feedback that there were few complaints about the Objective-C online compiler not working I decided to give it a try myself.
The 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:
6 is also an equilibrium index, because:
(The sum of zero elements is zero) so 7 is not an equilibrium index because it is not a valid index of sequence A.
Your challenge is to write a function int equilibrium(int A) that, given a sequence, returns its equilibrium index (any) or -1 if no equilibrium index exists. Assume that the sequence may be very long. The problem can be solved by using various approaches, the most common being simply to follow the equilibrium definition. Create an empty project and use the main.m file to run the code:
Here is the score I got using this approach:
It seems this approach was not efficient for two reasons:
it takes way too long to process large input data sets because time complexity is quadratic or O(n^2)
it fails on large input values (outside the int min/max limits) due to the arithmetic overflows
We can improve our algorithm by updating the left/right sums in O(1) constant time instead of recomputing them both at each iteration. To handle larger input values we should use a proper data-type such as long long instead of int. Here is a better solution:
Using this solution I got the perfect score:
Until next time!