Find Pivot Index
Real-world version: Beam Balance StationThe 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.
def balance_station(loads: list[int]) -> int:public int balanceStation(int[] loads)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 17 test cases: 17 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's