Given an array, find the leftmost index where the sum of all elements to its left equals the sum of all elements to its right. Return -1 if no such index exists.
Video coming soon
We're producing a video walkthrough — check back soon.
Given an array, find the leftmost index where the sum of all elements to its left equals the sum of all elements to its right. Return -1 if no such index exists.
The cleanest possible bridge from plain traversal into prefix-sum thinking: it looks like it needs two separate prefix and suffix arrays, but the total sum alone is enough to derive the right-hand side on the fly.
Whenever a problem compares a running left-hand quantity against a right-hand quantity that's 'everything else', check whether the right-hand side can be derived from the total minus what's already been tracked, instead of building a second array.
Compute the total sum of the array once. Then walk the array left to right with a running leftSum, initialized to 0. At each index i, the sum of everything to the right of i is total - leftSum - nums[i] (leftSum only accounts for elements strictly before i). If leftSum equals that derived right sum, index i is a valid pivot — since the scan moves left to right, the first match found is automatically the leftmost one. If no index matches by the end of the scan, add nums[i] to leftSum and continue; if the loop finishes with no match, return -1.
class Solution {
public int pivotIndex(int[] nums) {
int total = 0;
for (int num : nums) total += num;
int leftSum = 0;
for (int i = 0; i < nums.length; i++) {
int rightSum = total - leftSum - nums[i];
if (leftSum == rightSum) return i;
leftSum += nums[i];
}
return -1;
}
}