Leetcode 1991: Find the Middle Index in Array

grid47
grid47
Exploring patterns and algorithms
Apr 21, 2024 5 min read

Given a 0-indexed integer array ’nums’, find the leftmost index where the sum of elements to the left of that index is equal to the sum of elements to the right of that index. If such an index exists, return the smallest such index, otherwise return -1. The sum of the elements before the first index is considered 0, and similarly, the sum of elements after the last index is also 0.
Problem
Approach
Steps
Complexity
Input: The input consists of an array 'nums' where each element represents an integer.
Example: nums = [1, 2, 3, -1, 2]
Constraints:
• 1 <= nums.length <= 100
• -1000 <= nums[i] <= 1000
Output: Return the leftmost index where the sum of elements to the left equals the sum of elements to the right. If no such index exists, return -1.
Example: Output: 3
Constraints:
• The output should be an integer representing the leftmost index or -1 if no such index exists.
Goal: The goal is to find the leftmost index where the sum of elements to the left is equal to the sum of elements to the right.
Steps:
• Calculate the prefix sum for the input array, which is the cumulative sum of elements from the start up to each index.
• Compare the prefix sum at each index with the total sum to find the middle index where the two sides are balanced.
Goal: Ensure that the solution handles arrays of up to 100 elements efficiently.
Steps:
• The length of the array is small enough to use an approach that computes cumulative sums.
Assumptions:
• The input array is non-empty, and its length will be between 1 and 100.
Input: Input: nums = [1, 2, 3, -1, 2]
Explanation: The sum of elements to the left of index 3 is 1 + 2 + 3 = 6, and the sum of elements to the right is -1 + 2 = 6. Hence, index 3 is the middle index.

Input: Input: nums = [1, 2, 3]
Explanation: There is no index where the sum of elements to the left equals the sum of elements to the right, so the result is -1.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus