Drill

ProblemsGo › patterns

Where the ledger balances

mediumpatternsPrefix sumsArraysGo

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

balancingRow(rows: list<int>) → int

Go needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

func balancingRow(rows []int) int {
	
}

Worked examples

CallResult
balancingRow([]int{1, 7, 3, 6, 5, 6})3
balancingRow([]int{1, 2, 3})-1
balancingRow([]int{2, 1, -1})0
balancingRow([]int{-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 Go
func balancingRow(rows []int) int {
	whole := 0
	for _, value := range rows {
	    whole += value
	}
	left := 0
	for i, value := range rows {
	    if left == whole-left-value {
	        return i
	    }
	    left += value
	}
	return -1
}

The same problem in another language

More patterns problems in Go