Leetcode 1991. Find the Middle Index in Array
Find the Middle Index in Array
Given a 0-indexed integer array nums
, find the leftmost middleIndex (if exists) such that:
middleIndex
is equal to the sum of elements to the right of middleIndex
.If there is no such index, return -1. Note that middleIndex
should not be considered to be part of either the left sum or the right sum.
Example:
Input: nums = [2, 3, -1, 8, 4]
Output: 3
Explanation:
The sum of the numbers to the left of index 3 is: 2 + 3 + -1 = 4
The sum of the numbers to the right of index 3 is: 4 = 4
Can the array contain negative numbers? Yes, the array can contain negative as well as positive integers.
Will the array always have at least one element? Constraints typically state the array size, but let’s assume the array will have at least one element for now.
Are there any constraints on time complexity?
While no explicit constraints are provided, we should aim for an optimal solution. Ideally, a solution better than O(n^2)
should be considered.
To find the middle index, we can use the following approach:
leftSum
to 0. This will be used to store the sum of elements to the left of the current index.totalSum - leftSum - nums[i]
.leftSum
is equal to the right sum.leftSum
by adding the current element.Here’s the Java solution for the problem:
public class Solution {
public int findMiddleIndex(int[] nums) {
int totalSum = 0;
for (int num : nums) {
totalSum += num;
}
int leftSum = 0;
for (int i = 0; i < nums.length; i++) {
if (leftSum == totalSum - leftSum - nums[i]) {
return i;
}
leftSum += nums[i];
}
return -1;
}
}
leftSum
to 0.leftSum
.leftSum
to include the current element.The time complexity of this solution is O(n)
, where n
is the number of elements in the array. This is because we are iterating through the array twice:
The space complexity is O(1)
as we are using only a few extra variables.
This approach ensures that we find the solution efficiently.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?