This is a Rosetta Code post.
Story
A popular interview question/assessment is to find the equilibrium index of an array. Generally its to assess the candidates approach to a problem more so than actually solving it.
The equilibrium index of an array is an index where the sum of elements at lower indexes (to the left) is equal to the sum of elements at higher indexes (to the right). Should none of the above hold truth, the array has no equilibrium index.
Task
Given the following zero index array [2,2,4,1,3]
consisting of integers write a function that determines the equilibrium index. If an equilibrium index exists, return it. Else return -1.
For this example the its clear that the answer is A[2]
as shown below
1 | A[0] + A[1] = A[2] |
The step by step calculations shown from a simple to cognitively calculate array [1,2,3,4,5]
which has no equilibrium index would be as follows
1 | 1 = 1 |
Solutions
Pseudocode would be acceptable during an interview question but for an assessment I’d expect to see some code (points for unit tests!)
pseudocode
Simplest approach, probably in-efficient but good enough as a first cut.
1 | iterate over the collection with a for loop `i=0; i<a.len; i++` |
for
Probably not something we would ship to production but good enough to iterate on and refactor to a better design with unit tests. (we always write unit tests right? :D)
1 | for (int i = 0; i < _array.Length; i++) |
foreach
Code solution from rosettacode.org
1 | static IEnumerable<int> EquilibriumIndices(IEnumerable<int> sequence) |