This is a Rosetta Code post.
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.
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 as shown below
A + A = A
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
Pseudocode would be acceptable during an interview question but for an assessment I’d expect to see some code (points for unit tests!)
Simplest approach, probably in-efficient but good enough as a first cut.
iterate over the collection with a for loop `i=0; i<a.len; i++`
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)
for (int i = 0; i < _array.Length; i++)
Code solution from rosettacode.org
static IEnumerable<int> EquilibriumIndices(IEnumerable<int> sequence)