Find the balance point of a seesaw

Arrays, strings and hash maps Junior Python 3.13+ Reviewed By Best Latest Apps

Fill the blank

Fill the blank.

Python 3.13
def balance(w: list[int]) -> int:
    total, left = sum(w), 0
    for i, x in enumerate(w):
        if ____:
            return i
        left += x
    return -1
print(balance([1, 7, 3, 6, 5, 6]))

Options

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A left == total - left - x

Right: the right side is everything except the left side and the pivot itself.

For [1, 7, 3, 6, 5, 6] the left side at index 3 is 11 and the right side is 28 - 11 - 6 = 11.

Why not the others?
  • B left == total - left. This counts the pivot on the right side.
  • C left + x == total. That compares the left side plus the pivot with the whole total, which only holds when nothing is on the right, so it prints 5.

30-second answer

Compute the grand total once. Then walk left to right keeping the left total: the right total at index i is total - left - w[i]. The first index where they match is the answer. One pass after the sum, O(n) time and O(1) space.

Practise saying it · 30 s. No recording, just a timer

Explain how you find the balance point in one pass.

Say your answer out loud, then check which of these points you covered:

  • Total once
  • Right = total - left - w[i]
  • Update left after the check

Deep dive

Deriving the right side from the total avoids a second running sum or a suffix array.

Update the left total after the comparison, because index i belongs to neither side.

Negative weights are fine: nothing here relies on totals growing.

Python solution Ran on Python 3.13.5 · mypy --strict
Python 3.13
def balance_point(weights: list[int]) -> int:
    total, left = sum(weights), 0
    for i, w in enumerate(weights):
        if left == total - left - w:
            return i
        left += w
    return -1

Common mistakes

  • Adding w[i] to the left total before comparing, which shifts every answer by one.
  • Recomputing sum(w[:i]) and sum(w[i+1:]) at each index, which is O(n²).

Senior take & follow-ups

This is the prefix-sum idea in its smallest form. Name it, and the follow-ups about range sums become easy.

Follow-up questions

Think of your answer first, then open the hint.

  1. What if you need all balance points?

    Show hint

    Collect every matching index instead of returning the first.

  2. Can you answer many range-sum questions quickly?

    Show hint

    Build a prefix-sum array once; each range sum is then one subtraction.

What each operation costs: Arrays · Dynamic Arrays · Hash Table · Hash Functions

From the author

DSA Master - Data & Algorithms

Free on iPhone and iPad: watch 50+ data structures and algorithms step through animations, run the code in the playground, and try the daily challenge.

Suggest a fix if something here is wrong or out of date.