Show problems as
Classic problem #724EasyArrayPrefix Sum

Find Pivot Index

Real-world version: Beam Balance Station
Tracked in this browser only
Read Find Pivot Index on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A steel beam rests on a row of posts. The array loads gives the signed load measured at each post, listed in order along the beam. A negative reading means that post is being pulled upward rather than pressed down.

A post counts as a balance station when the readings on every post listed before it total exactly what the readings on every post listed after it total. The reading on the balance station itself belongs to neither side and is skipped. A post at either end of the row is still eligible, since a side with no posts on it totals zero.

Return the index of the earliest balance station on the beam. When several posts balance the beam, the smallest such index is the answer. When no post balances it, return -1.

Examples

Example 1

Input
loads = [5, -2, 9, 4, -1]
Output
2

Before index 2 the readings 5 and -2 total 3, and after it the readings 4 and -1 also total 3. The load of 9 on the station itself is skipped.

Example 2

Input
loads = [8, -3, 5]
Output
-1

No post splits the rest of the beam into two equally loaded sides, so the answer is -1.

Example 3

Input
loads = [0, 0, 0]
Output
0

Every post balances the beam here, so the earliest index wins.

Constraints

  • 1 <= loads.length <= 10^4
  • -1000 <= loads[i] <= 1000

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def balance_station(loads: list[int]) -> int:
Java
public int balanceStation(int[] loads)