You are given a 0-indexed integer array nums
. The middle index is any index i
such that nums[0] + nums[1] + ... + nums[i-1] == nums[i+1] + nums[i+2] + ... + nums[nums.length-1]
.
i
is the middle index, return i
, otherwise, return -1
.Input: nums = [2, 3, -1, 8, 4]
Output: 3
Explanation: The sum of the numbers before index 3
is 2 + 3 + -1 = 4
. The sum of the numbers after index 3
is 4 = 4
.
Input: nums = [1, -1, 4]
Output: 2
Explanation: The sum of the numbers before index 2
is 1 + -1 = 0
. The sum of the numbers after index 2
is an empty sum, which is 0
.
Input: nums = [2, 5]
Output: -1
Explanation: There is no valid middle index.
To find the middle index, we’ll keep track of the running sum from the start and the end of the array.
i
, the right sum can be derived by subtracting the left sum and the element at index i
from the total sum.-1
.def findMiddleIndex(nums):
total_sum = sum(nums)
left_sum = 0
for i, num in nums:
right_sum = total_sum - left_sum - num
if left_sum == right_sum:
return i
left_sum += num
return -1
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?