Given a 0-indexed integer array nums
, find the leftmost middleIndex
(i.e., the smallest amongst all the possible ones).
A middleIndex
is an index where nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1]
.
If middleIndex == 0
, the left side sum is considered to be 0
. Similarly, if middleIndex == nums.length - 1
, the right side sum is considered to be 0
.
Return the leftmost middleIndex
that satisfies the condition, or -1
if there is no such index.
LeetCode Problem - 1991
class Solution {
// Method to find the middle index in the given array
public int findMiddleIndex(int[] nums) {
int len = nums.length; // Get the length of the array
int[] sumLeft = new int[len]; // Array to store the sum of elements to the left of each index
int[] sumRight = new int[len]; // 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 < len; i++){
flag += nums[i];
sumLeft[i] = flag;
}
// Calculate the sum of elements to the right of each index
sumRight[len - 1] = nums[len - 1];
flag = nums[len - 1];
for(int i = len - 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 < len; i++){
if(sumRight[i] == sumLeft[i]) return i;
}
// If no middle index is found, return -1
return -1;
}
}