Python coding

Balance point of a list

Given a list of integers nums, return the smallest index i where the sum of the values strictly to the left of i equals the sum of the values strictly to its right. An empty side sums to 0. Return -1 if no index balances the list.

Values may be negative and nums may be empty. Aim for O(n): don't add up both sides again for every index.

Besides the tests, one large input (12,000 numbers) with a ~150 ms limit (scaled to your device's speed): brute force won't pass.

  • balance_index([3,1,5,2,2]) → 2
  • balance_index([2,5,4]) → -1
  • balance_index([3,4,-4]) → 0
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Adding up both sides for every index is O(n²). The left side grows by one value per step, and the right side is whatever the total leaves.

Hint 2

Compute total once and keep a running left. At index i the right side is total - left - nums[i]; add nums[i] to left only after comparing.

Solution and why it works
pythonO(n) · O(1)
def balance_index(nums: list[int]) -> int:
    total = sum(nums)
    left = 0                             # sum of everything before i
    for i, x in enumerate(nums):
        if left == total - left - x:     # right side = total - left - nums[i]
            return i
        left += x
    return -1

With the total known, the right side at i is total - left - nums[i], so one running sum checks every index in O(n) instead of adding up both sides each time. Order matters: compare first, then add nums[i] to left, because the index itself belongs to neither side. Returning at the first match gives the leftmost index. Negative values rule out shortcuts such as stopping once left passes half the total.