Find Pivot Index — LeetCode 724 Python Solution
- Problem
- #724
- Pattern
- Prefix Sum
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given an array of integers nums, calculate the pivot index of this array. The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right.
Example
- Input
- nums = [1,7,3,6,5,6]
- Output
- 3
- Explanation
- The pivot index is 3.
Python solution
class Solution:
def pivotIndex(self, nums: List[int]) -> int:
left, right = 0, sum(nums)
for i, x in enumerate(nums):
right -= x
if left == right:
return i
left += x
return -1Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(1) auxiliary |
Pattern: Prefix Sum
Precompute running totals once so any range query becomes a single subtraction. LeetCode 724. Find Pivot Index is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Prefix Sum.
The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.
Related problems
On a study list
This problem is on LeetCode 75.
Frequently asked questions
- How hard is LeetCode 724. Find Pivot Index?
- LeetCode 724. Find Pivot Index is rated Easy on LeetCode.
- What is the time complexity of LeetCode 724. Find Pivot Index?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 724. Find Pivot Index?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 724. Find Pivot Index cover?
- LeetCode 724. Find Pivot Index is tagged Array and Prefix Sum on LeetCode.