#1991

Find the Middle Index in Array

newbie · 290 · lc easy +20 · premium · verified · 69.2% accepted · 1,556 likes · top 77%

Description

In a 0-indexed integer array nums, an index is called a middleIndex when the sum of all elements before it equals the sum of all elements after it. Boundary cases: if the index is 0, the left sum is 0; if the index is nums.length - 1, the right sum is 0.

Find and return the smallest such middleIndex, or -1 if none exists.

Example 1:

Input: nums = [2,3,-1,8,4]
Output: 3
Explanation: The sum of the numbers before index 3 is: 2 + 3 + -1 = 4
The sum of the numbers after index 3 is: 4 = 4

Example 2:

Input: nums = [1,-1,4]
Output: 2
Explanation: The sum of the numbers before index 2 is: 1 + -1 = 0
The sum of the numbers after index 2 is: 0

Example 3:

Input: nums = [2,5]
Output: -1
Explanation: There is no valid middleIndex.

Code

1
2
3