↓Skip to main content
  1. LeetCode/

LeetCode 1991: Find the Middle Index in Array

·1 min· ·
LeetCode Easy Array Prefix-Sum
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-11-23

  • Submissions: Accepted (first try)

Approach
#

Compute total, maintain left from the left (Prefix Sum), and the right sum is total - left - nums[i]. The first position with left == right is the answer (the leftmost is required). It is the same problem as LC 724.

My Solution
#

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

Complexity
#

Time O(n), space O(1).

Mistakes to Avoid
#

  • Add nums[i] to left after comparing; the element itself belongs to neither side.

Interview Explanation
#

I compute the total and maintain the left sum; the right sum is the total minus the left and the current element, and the first match is the answer. Time O(n), space O(1).

Related

LeetCode 1413: Minimum Value to Get Positive Step by Step Sum
·1 min
LeetCode Easy Array Prefix-Sum
LeetCode 1413 note: the start value plus every prefix sum must be at least 1, so it is max(1, 1 - minimum prefix sum)
LeetCode 1480: Running Sum of 1d Array
·1 min
LeetCode Easy Array Prefix-Sum
LeetCode 1480 note: the definition of a prefix sum, adding each element to the previous running total
LeetCode 1732: Find the Highest Altitude
·1 min
LeetCode Easy Array Prefix-Sum
LeetCode 1732 note: the altitudes are prefix sums of gain starting from 0; take the maximum
LeetCode 1337: The K Weakest Rows in a Matrix
·1 min
LeetCode Easy Array Binary-Search Sorting Heap-Priority-Queue
LeetCode 1337 note: soldiers come first in each row, so binary search the first 0 for the count; sort by (count, row index) and take k
LeetCode 1160: Find Words That Can Be Formed by Characters
·1 min
LeetCode Easy Array Hash-Table String Counting
LeetCode 1160 note: a word is formable when none of its character counts exceeds chars’; sum the lengths of such words
LeetCode 1051: Height Checker
·1 min
LeetCode Easy Array Sorting Counting-Sort Bubble-Sort
LeetCode 1051 note: sort and count the positions that differ from the original