https://leetcode.com/problems/find-pivot-index/
- Prefix Sum
Compute total sum, then iterate tracking left sum. Pivot where left == total - left - nums[i].
O(n)
O(1)
class Solution {
public int pivotIndex(int[] nums) {
int total = 0;
for (int n : nums) total += n;
int left = 0;
for (int i = 0; i < nums.length; i++) {
if (left == total - left - nums[i]) return i;
left += nums[i];
}
return -1;
}
}