Find Pivot Index — LeetCode 724 Python Solution

EasyArrayPrefix Sum
Problem
#724
Pattern
Prefix Sum
Reading time
2 min

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

Python
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 -1

Complexity

MeasureComplexity
TimeO(n)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview