Find the Middle Index in Array
Python solution:


The approach here is to iterate over the array while keeping track of the sum of the elements on the left side (left_sum
) and the sum of the rest of the elements (total_sum
). For each index, if left_sum
is equal to total_sum
, return the index because that’s a valid “middle index” according to the problem’s definition. If no such index is found, the function returns 1.
Identifying Problem Isomorphism
This problem is same as problem 724. Find Pivot Index.
Yes, you’re correct. This problem is similar to the problem 724, “Find Pivot Index”, in LeetCode. Both problems involve finding an index in an array where the sum of the elements to the left of the index equals the sum of the elements to the right.
However, there is a slight variation in the definition of the pivot index and the middle index in the two problems. In problem 724, the pivot index is allowed to be the first or last index of the array (if the sum of the rest of the array is 0), while in this problem, the middle index is not allowed to be the first or last index.
The same approach can be used to solve both problems. The key idea is to maintain a running total of the elements in the array and a running total of the elements to the left of the current index. These totals can then be compared to identify if the current index is a pivot index or middle index.