Skip to the content

The balanced potion

Problem

In the alchemist's workshop, the ingredients sit in a row on a long board, and the board rests on one of them. If it tips, the potion is ruined. Some of them, like a phoenix feather, pull upward: they weigh a negative amount.

You get the list of weights, as whole numbers (it may be empty). Return the first position, counting from 0, where everything to its left adds up to the same as everything to its right. The ingredient it rests on counts on neither side, and a side with nothing on it adds up to 0: [5] gives 0. If there is no such position, or the list is empty, return -1.

With [1, 7, 3, 6, 5, 6] you return 3, because 1 + 7 + 3 = 5 + 6 = 11. A hint: don't add up both sides at every position. Add everything once, then keep a running total of the left; the right comes from subtracting.

Examples

  • Resting in the middle

    [1, 7, 3, 6, 5, 6] → 3

  • Three ingredients

    [2, 4, 2] → 1

  • It always tips

    [1, 2, 3] → -1

  • A single ingredient

    [5] → 0

  • An empty board

    [] → -1

Besides these, the challenge has hidden tests that are revealed when you submit your solution.

You start with this

Python

def balance_point(weights):
    pass

JavaScript

function balancePoint(weights) {
}
Solve this challenge

It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.

More O(n) challenges

See all challenges →