Find the Middle Index in Array - Problem
Given a 0-indexed integer array nums, find the leftmost middleIndex (i.e., the smallest amongst all the possible ones).
A middleIndex is an index where nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1].
If middleIndex == 0, the left side sum is considered to be 0. Similarly, if middleIndex == nums.length - 1, the right side sum is considered to be 0.
Return the leftmost middleIndex that satisfies the condition, or -1 if there is no such index.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [2,1,-1]
›
Output:
0
💡 Note:
At index 0: left sum = 0 (no elements), right sum = 1 + (-1) = 0. Since 0 = 0, return 0.
Example 2 — Middle Balance
$
Input:
nums = [2,3,1,0,4]
›
Output:
2
💡 Note:
At index 2: left sum = 2 + 3 = 5, right sum = 0 + 4 = 4. Not equal. At index 2: left sum = 2 + 3 = 5, right sum = 0 + 4 = 4. Continue checking...
Example 3 — No Balance Point
$
Input:
nums = [1,7,3,6,5,6]
›
Output:
-1
💡 Note:
No index satisfies the condition where left sum equals right sum.
Constraints
- 1 ≤ nums.length ≤ 104
- -1000 ≤ nums[i] ≤ 1000
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array [2,1,-1] where we need to find balance point
2
Process
Check each index for equal left and right sums
3
Output
Return leftmost index where balance exists
Key Takeaway
🎯 Key Insight: Use total sum to calculate right sum efficiently: rightSum = totalSum - leftSum - currentElement
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code