#724
Find Pivot Index
EasyArrayPrefix SumPrefix SumTwo Pointers
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 of the array and then iteratively checks for the pivot index by maintaining a running left sum. This avoids redundant calculations and reduces time complexity.
⚙️
Algorithm
6 steps- 1Step 1: Calculate the total sum of the array.
- 2Step 2: Initialize a variable 'leftSum' to 0.
- 3Step 3: Loop through each index 'i' in the array.
- 4Step 4: Calculate the right sum as total sum minus left sum minus the current element.
- 5Step 5: If left sum equals right sum, return the current index 'i'.
- 6Step 6: Update left sum by adding the current element and continue.
solution.py11 lines
1# Full working Python code
2
3def pivotIndex(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 twice: once to calculate the total sum and once to find the pivot index.
- 1Using a total sum allows us to avoid nested loops, significantly improving efficiency.
- 2Maintaining a running left sum helps us dynamically calculate the right sum without additional loops.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.