24. Balance Point
A seesaw has weights placed at evenly spaced positions along its plank, and the weight at each position is given in the array. A support can be placed directly under one position. It balances if the total weight to the left of the support equals the total weight to the right of it; the weight sitting on the support itself does not count for either side.
Write a method pivotIndex that takes the array nums of weights and returns the leftmost position where the support balances the plank. If no position balances it, return -1. An empty side counts as a total weight of 0.
Example 1
- Input:
- nums = [1,7,3,6,5,6]
- Output:
- 3
- Explanation:
At position 3 the left side adds up to 1 + 7 + 3 = 11 and the right side to 5 + 6 = 11.
Example 2
- Input:
- nums = [1,2,3]
- Output:
- -1
- Explanation:
No position has equal totals on both sides, so the answer is -1.
Constraints
1 ≤ nums.length ≤ 1000
-1000 ≤ nums[i] ≤ 1000
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n)
- Space
- O(1)