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 considered0 - If
middleIndex == nums.length - 1, the right side sum is considered0
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
Visualization
Time & Space Complexity
Two passes through the array: one to calculate total sum, one to find the middle index
Only using a few variables to track sums, no additional data structures
Constraints
- 1 โค nums.length โค 1000
- -1000 โค nums[i] โค 1000
- Note: Array can contain negative numbers