Drill

ProblemsTypeScript › patterns

Where the ledger balances

mediumpatternsPrefix sumsArraysTypeScript

An auditor looks for the row where everything above it and everything below it come to the same amount.

balancingRow(rows: list<int>) → int

Solve it in the editor →

Where you start

function balancingRow(rows: number[]): number {
  
}

Worked examples

CallResult
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 TypeScript
function balancingRow(rows: number[]): number {
  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;
}

The same problem in another language

More patterns problems in TypeScript