Split the Night Market

Easyprefix sumsAlso known as Find Pivot Index

A night market runs along one street. After closing, each stall reports its net result: positive for a profit, negative for a loss.

Two organizers share the street. They pick one dividing stall: stalls to its left go to one organizer, stalls to its right to the other, and the dividing stall counts for neither. They want both sides to total exactly the same.

Your task

Write fairSplit(results). Return the smallest index i such that the sum of results[0..i-1] equals the sum of results[i+1..end]. A side with no stalls sums to 0.

If no index works, or the list is empty, return -1.

fairSplit(results: int[]) → int

Examples

Example 1
Input
results = [2, 5, -1, 4, 3, 3]
Output
3
Why

Divide at index 3 (the stall that made 4). Left: 2 + 5 + (-1) = 6. Right: 3 + 3 = 6. No earlier index balances: at index 2, for example, the left is 7 and the right is 10.

Example 2
Input
results = [4, -4, 9]
Output
2
Why

Divide at the last stall, index 2. Left: 4 + (-4) = 0. Right: no stalls, so 0. The dividing stall can be at either end of the street.

Example 3
Input
results = [1, 2, 3]
Output
-1
Why

Index 0 gives 0 against 5, index 1 gives 1 against 3, index 2 gives 3 against 0. Nothing balances, so return -1.

Constraints

  • 0 ≤ results.length ≤ 100,000
  • -10,000 ≤ results[i] ≤ 10,000
Start with brute force

Try every index as the divider and add up both sides from scratch.

That is about n² additions: 10 billion for 100,000 stalls, nearly all repeated, since moving the divider one step only moves one stall between sides.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code