Leetcode 1991. Find the Middle Index in Array
Given a 0-indexed integer array nums
, find the leftmost middle index such that the sum of the elements on its left is equal to the sum of the elements on its right. If no such index exists, return -1
.
A middle index is an index where the sum of the elements to its left is equal to the sum of the elements to its right.
Q1. What should be considered the “left” and “right” of the middle index?
A1. The elements on the left of the middle index i
are those from index 0
to i-1
, and the elements on the right are those from index i+1
to the end of the array.
Q2. What is the range of values for the elements in the array and the length of the array?
A2. The elements of the array can be any integer, and the length of the array can range from 1
to 10^4
.
Q3. How should we handle a case where the array consists of only one element?
A3. If there’s only one element, the middle index is 0
by default because there are no elements on either side to compare.
-1
.#include <vector>
class Solution {
public:
int findMiddleIndex(std::vector<int>& nums) {
int totalSum = 0;
for (int num : nums) {
totalSum += num;
}
int leftSum = 0;
for (int i = 0; i < nums.size(); ++i) {
if (leftSum == totalSum - leftSum - nums[i]) {
return i;
}
leftSum += nums[i];
}
return -1;
}
};
Time Complexity: O(n), where n is the length of the array. We perform a single pass to compute the total sum and another pass to find the appropriate index, resulting in linear complexity.
Space Complexity: O(1), as we use only a few additional variables and no extra space proportional to the input size.
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?