i want to ask in this question which was ask by monu sir to complete it from home
here’s the code which a got from google ;-
class Solution {
public int pivotIndex(int[] nums) {
int totalSum = 0;
int leftSum = 0;
// Step 1: Calculate the total sum of the array
for (int num : nums) {
totalSum += num;
}
// Step 2: Iterate through the array to find the pivot
for (int i = 0; i < nums.length; i++) {
// Right sum is totalSum minus leftSum minus the current element
if (leftSum == totalSum - leftSum - nums[i]) {
return i; // Found the leftmost pivot index
}
// Update leftSum for the next iteration
leftSum += nums[i];
}
// No pivot index found
return -1;
}
}
why in step two we r calculating the right sum immediately , don’t we first need to calculate the left sum then minus this it from the total sum and what if we first calculate the prefix some then do the other task ?