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.
balancingRow(rows: list<int>) → int
Java 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.
Where you start
int balancingRow(List<Integer> rows) {
}
Worked examples
| Call | Result |
|---|---|
balancingRow(Main.<Integer>ls(1, 7, 3, 6, 5, 6)) | 3 |
balancingRow(Main.<Integer>ls(1, 2, 3)) | -1 |
balancingRow(Main.<Integer>ls(2, 1, -1)) | 0 |
balancingRow(Main.<Integer>ls(-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 Java
int balancingRow(List<Integer> rows) {
int whole = 0;
for (int value : rows) whole += value;
int left = 0;
for (int i = 0; i < rows.size(); i++) {
if (left == whole - left - rows.get(i)) return i;
left += rows.get(i);
}
return -1;
}