Skip to content

1991. Find the Middle Index in Array 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  int findMiddleIndex(vector<int>& nums) {
    int prefix = 0;
    int suffix = accumulate(nums.begin(), nums.end(), 0);

    for (int i = 0; i < nums.size(); ++i) {
      suffix -= nums[i];
      if (prefix == suffix)
        return i;
      prefix += nums[i];
    }

    return -1;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public int findMiddleIndex(int[] nums) {
    int prefix = 0;
    int suffix = Arrays.stream(nums).sum();

    for (int i = 0; i < nums.length; ++i) {
      suffix -= nums[i];
      if (prefix == suffix)
        return i;
      prefix += nums[i];
    }

    return -1;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def findMiddleIndex(self, nums: list[int]) -> int:
    prefix = 0
    suffix = sum(nums)

    for i, num in enumerate(nums):
      suffix -= num
      if prefix == suffix:
        return i
      prefix += num

    return -1