class Solution:
def pivotIndex(self, nums):
total = sum(nums)
left_sum = 0
for i, x in enumerate(nums):
if left_sum == (total - left_sum - x):
return i
left_sum += x
return -1
class Solution {
public:
int pivotIndex(vector<int>& nums) {
int total = 0, left_sum = 0;
for (int n : nums) total += n;
for (int i = 0; i < nums.size(); ++i) {
if (left_sum == total - left_sum - nums[i]) return i;
left_sum += nums[i];
}
return -1;
}
};
class Solution {
public int pivotIndex(int[] nums) {
int total = 0, leftSum = 0;
for (int n : nums) total += n;
for (int i = 0; i < nums.length; i++) {
if (leftSum == total - leftSum - nums[i]) return i;
leftSum += nums[i];
}
return -1;
}
}
var pivotIndex = function(nums) {
let total = nums.reduce((a, b) => a + b, 0);
let leftSum = 0;
for (let i = 0; i < nums.length; i++) {
if (leftSum === total - leftSum - nums[i]) return i;
leftSum += nums[i];
}
return -1;
};
Given an array of integers nums
, your task is to find the "pivot index" of this array. The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the right of the index.
-1
.nums.length
≤ 104nums[i]
≤ 1000Note: You cannot reuse elements; the left and right sums must exclude the element at the pivot index.
To solve this problem, the first idea that comes to mind is to check each index in the array and calculate the sum of elements to its left and the sum to its right. If these two sums are equal, we've found the pivot index. However, this approach would require two passes for each index (one for the left sum and one for the right sum), leading to a time complexity of O(n2), which is inefficient for large arrays.
To optimize, we realize that we can compute the total sum of the array once. Then, as we iterate through the array, we can keep a running sum of the left side. The sum of the right side can then be calculated as total_sum - left_sum - nums[i]
. If at any index the left sum equals the right sum, we've found our pivot.
This approach reduces the time complexity to O(n) and only needs a single pass through the array after calculating the total sum.
total
).left_sum
to 0. This will keep track of the sum of elements to the left of the current index.i
, check if left_sum == total - left_sum - nums[i]
.i
as the pivot index.nums[i]
to left_sum
and continue.-1
.This algorithm is efficient because:
Let's consider the example nums = [1, 7, 3, 6, 5, 6]
.
The optimized approach is efficient and suitable for large arrays.
The Find Pivot Index problem tests your ability to balance subarray sums efficiently. By leveraging the total sum of the array and keeping a running left sum, we can check the pivot condition in a single pass. This avoids unnecessary repeated summing and results in a clean, O(n) solution. The key insight is realizing that the right sum at any index is simply the total sum minus the left sum and the current element.