Given a 0-indexed integer array nums, find the leftmostmiddleIndex (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 _theleftmost _middleIndexthat satisfies the condition, or-1if there is no such index.
We want to find the leftmost index where the sum of elements to the left equals the sum of elements to the right. By precomputing the total sum and using a running prefix sum, we can check this condition efficiently for each index.
classSolution {
publicintfindMiddleIndex(int[] nums) {
int total = 0, pre = 0;
for(int x : nums) total += x;
for(int i=0;i<nums.length;++i) {
if(pre == total-pre-nums[i]) return i;
pre += nums[i];
}
return-1;
}
}
1
2
3
4
5
6
7
8
9
10
classSolution {
funfindMiddleIndex(nums: IntArray): Int {
val total = nums.sum(); var pre = 0for(i in nums.indices) {
if(pre == total-pre-nums[i]) return i
pre += nums[i]
}
return -1 }
}
1
2
3
4
5
6
7
8
9
classSolution:
deffindMiddleIndex(self, nums: list[int]) -> int:
total = sum(nums)
pre =0for i, x in enumerate(nums):
if pre == total - pre - x:
return i
pre += x
return-1
1
2
3
4
5
6
7
8
9
10
11
impl Solution {
pubfnfind_middle_index(nums: Vec<i32>) -> i32 {
let total: i32= nums.iter().sum();
letmut pre =0;
for (i, &x) in nums.iter().enumerate() {
if pre == total - pre - x { return i asi32; }
pre += x;
}
-1 }
}