Find the Middle Index in Array - Problem

Imagine you're standing on a balance beam trying to find the perfect equilibrium point. In this problem, you need to find the leftmost middle index in an integer array where the sum of elements on the left equals the sum of elements on the right.

Given a 0-indexed integer array nums, your task is to find the smallest index middleIndex such that:

  • nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1]

Special cases:

  • If middleIndex == 0, the left side sum is considered 0
  • If middleIndex == nums.length - 1, the right side sum is considered 0

Return the leftmost middleIndex that satisfies the condition, or -1 if no such index exists.

Example: For array [2, 3, -1, 8, 4], index 3 is the middle index because left sum = 2+3+(-1) = 4 and right sum = 4.

Input & Output

example_1.py โ€” Basic Case
$ Input: [2, 3, -1, 8, 4]
โ€บ Output: 3
๐Ÿ’ก Note: At index 3, left sum = 2 + 3 + (-1) = 4, right sum = 4. Both sums are equal, so index 3 is the middle index.
example_2.py โ€” No Middle Index
$ Input: [1, -1, 4]
โ€บ Output: -1
๐Ÿ’ก Note: No index satisfies the condition. At index 0: left=0, right=3. At index 1: left=1, right=4. At index 2: left=0, right=0. None have equal left and right sums.
example_3.py โ€” Edge Case - Single Element
$ Input: [2]
โ€บ Output: 0
๐Ÿ’ก Note: For a single element array, index 0 is the middle index since both left sum (0) and right sum (0) are equal.

Visualization

Tap to expand
Finding the Perfect Seesaw BalanceGround LevelFulcrum at Index 323-1Left Side = 44Right Side = 4BALANCED!4 = 4Answer: Index 3 is the perfect balance point!
Understanding the Visualization
1
Calculate Total Weight
Sum all children's weights: 2+3+(-1)+8+4 = 16 units
2
Try Each Position
Move the fulcrum and check if both sides balance
3
Found Balance
At position 3, left weight (4) equals right weight (4)
Key Takeaway
๐ŸŽฏ Key Insight: Instead of recalculating sums repeatedly, use the mathematical relationship: right_sum = total_sum - left_sum - current_element to find the balance point efficiently in O(n) time.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Two passes through the array: one to calculate total sum, one to find the middle index

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only using a few variables to track sums, no additional data structures

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 1000
  • -1000 โ‰ค nums[i] โ‰ค 1000
  • Note: Array can contain negative numbers
Asked in
Amazon 45 Microsoft 38 Google 32 Meta 28
67.2K Views
High Frequency
~15 min Avg. Time
1.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