#1991
Find the Middle Index in Array
EasyArrayPrefix SumPrefix SumArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal approach uses a single pass to calculate the total sum and then iteratively checks each index while maintaining the left sum. This avoids redundant calculations and reduces time complexity.
⚙️
Algorithm
5 steps- 1Step 1: Calculate the total sum of the array.
- 2Step 2: Initialize a variable for left sum as 0.
- 3Step 3: Loop through each index and update the right sum by subtracting the current element from total sum.
- 4Step 4: If left sum equals right sum, return the current index.
- 5Step 5: Update left sum by adding the current element before moving to the next index.
solution.py11 lines
1# Full working Python code
2
3def findMiddleIndex(nums):
4 total_sum = sum(nums)
5 left_sum = 0
6 for i in range(len(nums)):
7 right_sum = total_sum - left_sum - nums[i]
8 if left_sum == right_sum:
9 return i
10 left_sum += nums[i]
11 return -1ℹ
Complexity note: This complexity is achieved because we only traverse the array a constant number of times (once for total sum and once for checking middle index).
- 1Using prefix sums can significantly reduce the number of calculations needed.
- 2Iterating through the array while maintaining a running total allows for efficient checks.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.