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.
balancing_row(rows: list<int>) → int
Where you start
def balancing_row(rows: list[int]) -> int:
Worked examples
| Call | Result |
|---|---|
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