Drill

ProblemsC# › patterns

Where the ledger balances

mediumpatternsPrefix sumsArraysC#

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

BalancingRow(rows: list<int>) → int

C# 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

public int BalancingRow(List<int> rows) {
    
}

Worked examples

CallResult
BalancingRow(new List<int> { 1, 7, 3, 6, 5, 6 })3
BalancingRow(new List<int> { 1, 2, 3 })-1
BalancingRow(new List<int> { 2, 1, -1 })0
BalancingRow(new List<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 C#
public int BalancingRow(List<int> rows) {
    int whole = 0;
    foreach (var value in rows) whole += value;
    int left = 0;
    for (int i = 0; i < rows.Count; i++) {
        if (left == whole - left - rows[i]) return i;
        left += rows[i];
    }
    return -1;
}

The same problem in another language

More patterns problems in C#