Skip to content

Instantly share code, notes, and snippets.

@dolvik
Last active May 26, 2016 14:23
Show Gist options
  • Save dolvik/48da0fa78e0f08ab4b4e to your computer and use it in GitHub Desktop.
Save dolvik/48da0fa78e0f08ab4b4e to your computer and use it in GitHub Desktop.
Equilibrium index
"use strict";
//An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices.
//two loops
function eq(arr) {
if (arr.length === 0) {
return -1;
}
for (var i = 0; i < arr.length; i++) {
var lsum = 0;
var rsum = 0;
for (var j = 0; j < arr.length; j++) {
if (j < i) {
lsum += arr[j];
} else if (j > i) {
rsum += arr[j];
}
}
if (lsum === rsum) {
return i;
}
};
return -1;
}
//three loops
function eq2(arr) {
if (arr.length === 0) {
return -1;
}
for (var i = 0; i < arr.length; i++) {
var lsum, rsum;
lsum = rsum = 0;
for (var j = 0; j < i; j++) {
lsum += arr[j];
}
for (var k = i + 1; k < arr.length; k++) {
rsum += arr[k];
}
if (lsum === rsum) {
return i;
}
}
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment