You get an integer array nums. An index i is a pivot when the numbers before it add up to the same total as the numbers after it. The value at i itself belongs to neither side.
A side with no numbers adds up to 0, so index 0 is a pivot when everything after it sums to 0, and the last index is a pivot when everything before it sums to 0.
Return the smallest pivot index, or -1 when there is none.
Example 1
Input: nums = [3, 1, 5, 2, 2] Output: 2 Why: 3 + 1 = 4 on the left and 2 + 2 = 4 on the right
2 more examples and the constraints
Example 2
Input: nums = [4, -2, 3] Output: -1 Why: the sides are 0|1, 4|3 and 2|0; none match
Example 3
Input: nums = [6, -3, 3] Output: 0 Why: nothing on the left is 0, and -3 + 3 = 0
Constraints
- 1 ≤ nums.length ≤ 10,000
- -1,000 ≤ nums[i] ≤ 1,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Add up both sides for each indexO(n²)
- Total minus a running left sumO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Additions for 10,000 numbers | Verdict |
|---|---|---|---|
| Add up both sides for each index | O(n²) | Correct, but redoes the sums | |
| Total minus a running left sum | O(n) | Best; two short passes |
n = length of nums.
Edge cases to test
- Pivot at index 0. In [6, -3, 3] the left side is empty, so it counts as 0, and the right side is 0 too.
- Pivot at the last index. In [-2, 2, 9] the numbers before index 2 cancel out, so the answer is 2.
- A single number. Both sides are empty, so index 0 is always the pivot.
- Several pivots. In [0, 0, 0] every index works; return the smallest, 0.
- No pivot. Return -1, for example on [4, -2, 3].
Common mistakes
- Counting
nums[i]in the left or right sum. The pivot value belongs to neither side. - Adding
nums[i]toleftbefore the comparison instead of after it. - Returning the last pivot found instead of the first one.
How to talk through it
- 1Clarify. Does the value at the index count on either side? Which pivot do I return if there are several?
- 2Give the brute force. Add up both sides for every index; O(n²).
- 3Spot the waste. Neighbouring indexes share almost the same sums; only one number changes side.
- 4Use the total. Right equals total minus left minus the current value, so one running sum is enough.
- 5Test out loud. Try a pivot at index 0, a pivot at the end, a single number and an array with no pivot.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?