Skip to content

Commit b81da0f

Browse files
Find the Middle Index in Array
1 parent 12904b9 commit b81da0f

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
'''
2+
Given a 0-indexed integer array nums, find the leftmost middleIndex (i.e., the smallest amongst all the possible ones).
3+
A middleIndex is an index where nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1].
4+
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.
5+
Return the leftmost middleIndex that satisfies the condition, or -1 if there is no such index.
6+
7+
Example 1:
8+
Input: nums = [2,3,-1,8,4]
9+
Output: 3
10+
Explanation: The sum of the numbers before index 3 is: 2 + 3 + -1 = 4
11+
The sum of the numbers after index 3 is: 4 = 4
12+
13+
Example 2:
14+
Input: nums = [1,-1,4]
15+
Output: 2
16+
Explanation: The sum of the numbers before index 2 is: 1 + -1 = 0
17+
The sum of the numbers after index 2 is: 0
18+
19+
Example 3:
20+
Input: nums = [2,5]
21+
Output: -1
22+
Explanation: There is no valid middleIndex.
23+
24+
Constraints:
25+
1 <= nums.length <= 100
26+
-1000 <= nums[i] <= 1000
27+
'''
28+
29+
class Solution:
30+
def findMiddleIndex(self, nums: List[int]) -> int:
31+
left_sum = 0
32+
right_sum = sum(nums)
33+
34+
for i, num in enumerate(nums):
35+
if left_sum == right_sum - num:
36+
return i
37+
38+
left_sum += num
39+
right_sum -= num
40+
41+
return -1

0 commit comments

Comments
 (0)