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: -1
💡 Note: No index satisfies the condition. At index 0: left=0, right=8. At index 1: left=2, right=5. At index 2: left=5, right=4. At index 3: left=6, right=4. At index 4: left=6, right=0.
Example 3 — No Balance Point
$ Input: nums = [1,7,3,6,5,6]
Output: 3
💡 Note: At index 3: left sum = 1 + 7 + 3 = 11, right sum = 5 + 6 = 11. Since 11 = 11, return 3.

Constraints

  • 1 ≤ nums.length ≤ 104
  • -1000 ≤ nums[i] ≤ 1000

Visualization

Tap to expand
Find the Middle Index in Array INPUT nums = [2, 1, -1] 2 idx: 0 1 idx: 1 -1 idx: 2 Find index where: leftSum == rightSum Left Sum [0..mid-1] == Right Sum [mid+1..n-1] Total Sum = 2+1+(-1) = 2 ALGORITHM STEPS 1 Calculate Total Sum totalSum = 2+1+(-1) = 2 2 Init leftSum = 0 Start from index 0 3 Check Each Index rightSum = total-left-nums[i] 4 Compare Sums If left == right, return i Execution Trace: i=0: left=0, right=2-0-2=0 0 == 0 --> OK! Return 0 If not found at i=0: i=1: left=2, right=2-2-1=-1 i=2: left=3, right=2-3-(-1)=0 FINAL RESULT Middle Index Found! 2 idx: 0 1 idx: 1 -1 idx: 2 Verification at index 0: Left Sum = 0 (empty) Right Sum = 1+(-1) = 0 0 == 0 -- OK! Output: 0 Leftmost middle index Key Insight: Instead of calculating sums separately for each index, use the formula: rightSum = totalSum - leftSum - nums[i]. This gives O(n) time complexity with O(1) space. Update leftSum by adding nums[i] after each check. TutorialsPoint - Find the Middle Index in Array | Optimal Solution
Asked in
Amazon 45 Microsoft 32 Facebook 28 Google 21
125.0K Views
Medium Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen