Pivot Index of an Array
Problem
Find the leftmost index p such that the sum of all elements strictly to its left equals the sum of all elements strictly to its right. If no such index exists, return -1. The element at p itself is excluded from both sides.
Input
nums = [2, 4, 1, 7, 3, 5]Output
3Left of index 3: 2 + 4 + 1 = 7. Right of index 3: 3 + 5 = 8. They are not equal at index 3 — but at no index do they match in this example, so the actual return is -1. (Try [1, 7, 3, 6, 5, 6] for a true pivot at index 3.)
def pivot_index(nums):
total = sum(nums)
left = 0
for i, x in enumerate(nums):
right = total - left - x
if left == right:
return i
left += x
return -1
function pivotIndex(nums) {
let total = 0;
for (const x of nums) total += x;
let left = 0;
for (let i = 0; i < nums.length; i++) {
const right = total - left - nums[i];
if (left === right) return i;
left += nums[i];
}
return -1;
}
class Solution {
public int pivotIndex(int[] nums) {
int total = 0;
for (int x : nums) total += x;
int left = 0;
for (int i = 0; i < nums.length; i++) {
int right = total - left - nums[i];
if (left == right) return i;
left += nums[i];
}
return -1;
}
}
int pivotIndex(vector<int>& nums) {
int total = 0;
for (int x : nums) total += x;
int left = 0;
for (int i = 0; i < (int)nums.size(); i++) {
int right = total - left - nums[i];
if (left == right) return i;
left += nums[i];
}
return -1;
}