Leetcode 724. Find Pivot Index
The problem is to find the pivot index of an array. The pivot index is defined as an index i
such that the sum of the elements to the left of i
is equal to the sum of the elements to the right of i
. If no such index exists, return -1. If there are multiple pivot indexes, you should return the left-most pivot index.
nums = [1, 7, 3, 6, 5, 6]
3
Explanation:
The pivot index is 3.
Left sum: 1 + 7 + 3
= 11
Right sum: 5 + 6
= 11
nums = [1, 2, 3]
-1
nums
will be in the range [0, 10000]
.nums[i]
will be an integer in the range [-1000, 1000]
.totalSum - leftSum - nums[i]
.i
, check if the left sum equals the right sum.Here’s the implementation in C++:
#include <vector>
#include <numeric> // for std::accumulate
class Solution {
public:
int pivotIndex(std::vector<int>& nums) {
int totalSum = std::accumulate(nums.begin(), nums.end(), 0);
int leftSum = 0;
for (int i = 0; i < nums.size(); ++i) {
if (leftSum == totalSum - leftSum - nums[i]) {
return i;
}
leftSum += nums[i];
}
return -1;
}
};
The time complexity of this algorithm is O(n), where n
is the number of elements in the input array nums
. This is because we traverse the array twice (once for calculating totalSum
and once for finding the pivot index). The space complexity is O(1) since we are using a fixed amount of extra space.
This approach efficiently finds the pivot index, leveraging a single scan of the array to check each candidate index while maintaining a running sum of the left-hand side.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?