Problems › JavaScript › patterns
Where the ledger balances
An auditor looks for the row where everything above it and everything below it come to the same amount.
- The row itself belongs to neither side.
- Return the position of the leftmost row where the two sides match.
- The first and last rows count: one side of them is empty, which totals zero.
- If no row balances, return -1.
balancingRow(rows: list<int>) → int
Where you start
function balancingRow(rows) {
}
Worked examples
| Call | Result |
|---|---|
balancingRow([1,7,3,6,5,6]) | 3 |
balancingRow([1,2,3]) | -1 |
balancingRow([2,1,-1]) | 0 |
balancingRow([-1,1,2]) | 2 |
Hint
You know the whole total up front. Walk once carrying the left total, and the right side is the whole less the left less the row you are standing on.
Reference solution in JavaScript
function balancingRow(rows) {
let whole = 0;
for (const value of rows) whole += value;
let left = 0;
for (let i = 0; i < rows.length; i += 1) {
if (left === whole - left - rows[i]) return i;
left += rows[i];
}
return -1;
}