1991. Find the Middle Index in Array
Given array nums, return the leftmost middle index where sum of elements to the left equals sum of elements to the right. Return -1 if none exists.
Approach: compute total sum upfront, then walk left to right tracking running left sum; right sum derived as sum - left_sum - nums[i].
#![allow(unused)]
fn main() {
// time O(n), space O(1)
pub fn find_middle_index(nums: Vec<i32>) -> i32 {
let sum: i32 = nums.iter().sum();
let mut left_sum: i32 = 0;
for i in 0..nums.len() {
let right_sum = sum - left_sum - nums[i];
if left_sum == right_sum {
return i as i32;
}
left_sum += nums[i];
}
-1
}
}