Find the Middle Index in Array

easy array prefix sum

Problem

Given an array of integers nums, return the leftmost index i such that the sum of the elements strictly to the left of i equals the sum of the elements strictly to the right of i. The element at i itself counts for neither side, and an empty side is treated as a sum of 0. If no such index exists, return -1.

Inputnums = [2, 3, -1, 8, 4]
Output3
Left of index 3 is 2 + 3 + (-1) = 4, and right of index 3 is 4. Both sides match, so the answer is 3.

def find_middle_index(nums):
    total = sum(nums)
    left = 0
    for i, x in enumerate(nums):
        right = total - left - x
        if left == right:
            return i
        left += x
    return -1
function findMiddleIndex(nums) {
  const total = nums.reduce((a, b) => a + b, 0);
  let left = 0;
  for (let i = 0; i < nums.length; i++) {
    const right = total - left - nums[i];
    if (left === right) return i;
    left += nums[i];
  }
  return -1;
}
class Solution {
    public int findMiddleIndex(int[] nums) {
        int total = 0;
        for (int x : nums) total += x;
        int left = 0;
        for (int i = 0; i < nums.length; i++) {
            int right = total - left - nums[i];
            if (left == right) return i;
            left += nums[i];
        }
        return -1;
    }
}
int findMiddleIndex(vector<int>& nums) {
    int total = 0;
    for (int x : nums) total += x;
    int left = 0;
    for (int i = 0; i < (int)nums.size(); i++) {
        int right = total - left - nums[i];
        if (left == right) return i;
        left += nums[i];
    }
    return -1;
}
Time: O(n) Space: O(1)