Find the Middle Index in Array — LeetCode 1991 Python Solution

EasyArrayPrefix Sum
Problem
#1991
Pattern
Prefix Sum
Reading time
2 min

The problem

Given a 0-indexed integer array nums, find the leftmost middleIndex (i.e., the smallest amongst all the possible ones). A middleIndex is an index where nums[0] + nums[1] + ...

Example

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

Python solution

Python
class Solution:
    def findMiddleIndex(self, nums: List[int]) -> int:
        l, r = 0, sum(nums)
        for i, x in enumerate(nums):
            r -= x
            if l == r:
                return i
            l += x
        return -1

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array \textit{nums}
SpaceO(1) auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 1991. Find the Middle Index in Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Prefix Sum.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1991. Find the Middle Index in Array?
LeetCode 1991. Find the Middle Index in Array is rated Easy on LeetCode.
What is the time complexity of LeetCode 1991. Find the Middle Index in Array?
The Python solution on this page runs in O(n), where n is the length of the array \textit{nums}.
What is the space complexity of LeetCode 1991. Find the Middle Index in Array?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1991. Find the Middle Index in Array cover?
LeetCode 1991. Find the Middle Index in Array is tagged Array and Prefix Sum on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview