Keep a running left sum and derive the right sum from the array total at each position.
Complexity
O(n) time and O(1) extra space.
Find the leftmost index whose left and right element sums are equal.
Keep a running left sum and derive the right sum from the array total at each position.
O(n) time and O(1) extra space.
package main
func pivotIndex(nums []int) int {
total := 0
for _, value := range nums {
total += value
}
left := 0
for index, value := range nums {
if left == total-left-value {
return index
}
left += value
}
return -1
}
class Solution:
def pivotIndex(self, nums: list[int]) -> int:
total, left = sum(nums), 0
for index, value in enumerate(nums):
if left == total - left - value: return index
left += value
return -1
function pivotIndex(nums: number[]): number {
const total = nums.reduce((sum, value) => sum + value, 0);
let left = 0;
for (let index = 0; index < nums.length; index += 1) {
if (left === total - left - nums[index]) return index;
left += nums[index];
}
return -1;
}