Given an array of integers nums
, calculate 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 index's right.
If the index is on the left edge of the array, then the left sum is 0
because there are no elements to the left. This also applies to the right edge of the array.
Return the leftmost pivot index. If no such index exists, return -1
.
LeetCode Problem - 724
class Solution {
// Method to find the pivot index in the given array
public int pivotIndex(int[] nums) {
int[] sumLeft = new int[nums.length]; // Array to store the sum of elements to the left of each index
int[] sumRight = new int[nums.length]; // Array to store the sum of elements to the right of each index
// Calculate the sum of elements to the left of each index
sumLeft[0] = nums[0];
int flag = nums[0];
for(int i = 1; i < nums.length; i++){
flag += nums[i];
sumLeft[i] = flag;
}
// Calculate the sum of elements to the right of each index
sumRight[sumRight.length - 1] = nums[nums.length - 1];
flag = nums[nums.length - 1];
for(int i = (nums.length - 2); i >= 0; i--){
flag += nums[i];
sumRight[i] = flag;
}
// Check at which index sumRight[i] and sumLeft[i] are equal and return
for(int i = 0; i < nums.length; i++){
if(sumRight[i] == sumLeft[i]) return i;
}
// If no pivot index is found, return -1
return -1;
}
}