LeetCode 1991: Find the Middle Index in Array Solution
Master LeetCode problem 1991 (Find the Middle Index in Array), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1991. Find the Middle Index in Array
Problem Explanation
Explanation
To solve this problem, we can iterate through the array and check if the sum of elements on the left side of the current index is equal to the sum of elements on the right side. We can do this by maintaining prefix sums for both sides of the array. If we find a middle index that satisfies the condition, we return it. If no such index exists, we return -1.
- Start by calculating the total sum of the array.
- Iterate through the array and check if the sum of elements on the left side is equal to the sum of elements on the right side.
- Keep updating the left side sum and right side sum as we move through the array.
- Return the leftmost middle index that satisfies the condition.
Time Complexity: O(n) where n is the number of elements in the input array.
Space Complexity: O(1) as we are using constant space.
Solution Code
class Solution {
public int findMiddleIndex(int[] nums) {
int totalSum = 0;
for (int num : nums) {
totalSum += num;
}
int leftSum = 0;
int rightSum = totalSum;
for (int i = 0; i < nums.length; i++) {
rightSum -= nums[i];
if (leftSum == rightSum) {
return i;
}
leftSum += nums[i];
}
return -1;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1991 (Find the Middle Index in Array)?
This page provides optimized solutions for LeetCode problem 1991 (Find the Middle Index in Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1991 (Find the Middle Index in Array)?
The time complexity for LeetCode 1991 (Find the Middle Index in Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1991 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1991 in Java, C++, or Python.