* feat(tools): add seed/solution restore script * chore(curriculum): remove empty sections' markers * chore(curriculum): add seed + solution to Chinese * chore: remove old formatter * fix: update getChallenges parse translated challenges separately, without reference to the source * chore(curriculum): add dashedName to English * chore(curriculum): add dashedName to Chinese * refactor: remove unused challenge property 'name' * fix: relax dashedName requirement * fix: stray tag Remove stray `pre` tag from challenge file. Signed-off-by: nhcarrigan <nhcarrigan@gmail.com> Co-authored-by: nhcarrigan <nhcarrigan@gmail.com>
2.6 KiB
id, title, challengeType, forumTopicId, dashedName
id | title | challengeType | forumTopicId | dashedName |
---|---|---|---|---|
5987fd532b954e0f21b5d3f6 | Equilibrium index | 5 | 302255 | equilibrium-index |
--description--
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.
For example, in a sequence A
:
- $A_0 = -7$
- $A_1 = 1$
- $A_2 = 5$
- $A_3 = 2$
- $A_4 = -4$
- $A_5 = 3$
- $A_6 = 0$
3
is an equilibrium index, because:
- $A_0 + A_1 + A_2 = A_4 + A_5 + A_6$
6
is also an equilibrium index, because:
- $A_0 + A_1 + A_2 + A_3 + A_4 + A_5 = 0$
(sum of zero elements is zero)
7
is not an equilibrium index, because it is not a valid index of sequence A
.
--instructions--
Write a function that, given a sequence, returns its equilibrium indices (if any).
Assume that the sequence may be very long.
--hints--
equilibrium
should be a function.
assert(typeof equilibrium === 'function');
equilibrium([-7, 1, 5, 2, -4, 3, 0])
should return [3,6]
.
assert.deepEqual(equilibrium(equilibriumTests[0]), ans[0]);
equilibrium([2, 4, 6])
should return []
.
assert.deepEqual(equilibrium(equilibriumTests[1]), ans[1]);
equilibrium([2, 9, 2])
should return [1]
.
assert.deepEqual(equilibrium(equilibriumTests[2]), ans[2]);
equilibrium([1, -1, 1, -1, 1, -1, 1])
should return [0,1,2,3,4,5,6]
.
assert.deepEqual(equilibrium(equilibriumTests[3]), ans[3]);
equilibrium([1])
should return [0]
.
assert.deepEqual(equilibrium(equilibriumTests[4]), ans[4]);
equilibrium([])
should return []
.
assert.deepEqual(equilibrium(equilibriumTests[5]), ans[5]);
--seed--
--after-user-code--
const equilibriumTests =
[[-7, 1, 5, 2, -4, 3, 0], // 3, 6
[2, 4, 6], // empty
[2, 9, 2], // 1
[1, -1, 1, -1, 1, -1, 1], // 0,1,2,3,4,5,6
[1], // 0
[] // empty
];
const ans = [[3, 6], [], [1], [0, 1, 2, 3, 4, 5, 6], [0], []];
--seed-contents--
function equilibrium(a) {
}
--solutions--
function equilibrium(a) {
let N = a.length,
i,
l = [],
r = [],
e = [];
for (l[0] = a[0], r[N - 1] = a[N - 1], i = 1; i < N; i++)
{ l[i] = l[i - 1] + a[i], r[N - i - 1] = r[N - i] + a[N - i - 1]; }
for (i = 0; i < N; i++)
{ if (l[i] === r[i]) e.push(i); }
return e;
}