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 for the evening: a positive number for a profit, a negative one for a loss.

Two organizers share the street. They pick one stall as the dividing line: everything to its left belongs to one organizer, everything to its right to the other, and the dividing stall itself is the market's own and counts for neither. They want a dividing stall that makes both sides 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 with two loops.

Each try reads the whole list, so the cost is about n² additions. With 100,000 stalls that is 10 billion additions, nearly all of them repeated from the previous try: moving the divider one step only moves one stall from one side to the other.

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