A dockyard's cargo manifest lists n containers in loading order, and each container has an integer weight (weights can be negative, representing ballast removed at that step). A 0-indexed position i on the manifest is called a balance point if the sum of the weights of all containers loaded strictly before position i equals the sum of the weights of all containers loaded strictly after position i (the container at position i itself is excluded from both sides; an empty side sums to 0). Find the smallest index that is a balance point, or report that none exists.
Line 1: an integer n, the number of containers. Line 2: n space-separated integers, the weights of the containers in loading order.
A single integer: the smallest 0-indexed balance point, or -1 if no balance point exists.
Example 1
Input
5 2 3 -1 8 4
Expected
3
Explanation
At index 3, the weights before it sum to 2+3-1=4 and the weights after it sum to 4. These are equal, and no smaller index (0, 1, or 2) satisfies the balance condition, so the answer is 3.
Example 2
Input
3 1 -1 4
Expected
2
Explanation
At index 2, the sum before is 1-1=0 and there is nothing after, which also sums to 0, so they are equal. Indices 0 and 1 do not balance, so the smallest balance point is 2.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →