Find the Middle Index in Array — LeetCode 1991 Python Solution
- Problem
- #1991
- Pattern
- Prefix Sum
- Reading time
- 2 min
- Source
- leetcode.com
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
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 -1Complexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the array \textit{nums} |
| Space | O(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.