Drill

ProblemsPython › patterns

Where the ledger balances

mediumpatternsPrefix sumsArraysPython

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

balancing_row(rows: list<int>) → int

Solve it in the editor →

Where you start

def balancing_row(rows: list[int]) -> int:
    

Worked examples

CallResult
balancing_row([1, 7, 3, 6, 5, 6])3
balancing_row([1, 2, 3])-1
balancing_row([2, 1, -1])0
balancing_row([-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 Python
def balancing_row(rows: list[int]) -> int:
    whole = sum(rows)
    left = 0
    for i, value in enumerate(rows):
        if left == whole - left - value:
            return i
        left += value
    return -1

The same problem in another language

More patterns problems in Python