Python 0724.py
class Solution:
def pivotIndex(self, nums: List[int]) -> int:
total = sum(nums)
left = 0
for i in range(len(nums)):
right = total - left - nums[i]
if left == right:
return i
left += nums[i]
return -1
Difficulty
and has an acceptance rate of about 62% (2+ million submissions).
Typical patterns to solve this problem:
- Array
- Prefix Sum
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The presented implementation defines a method that determines a pivot index within an integer array. A pivot index is defined as a position where the sum of all elements to its left equals the sum of all elements to its right. The algorithm returns the first such index it encounters, or -1 if no such position exists.
Key Steps
Compute total sum
The algorithm begins by calculating the aggregate of all elements in the input list. This single value represents the combined contribution of the entire array and is later used to infer the right-hand sum without additional traversal.
total = sum(nums)
Initialize left accumulator
A variable is introduced to keep track of the cumulative sum of elements that appear before the current index during iteration. It starts at zero because there are no elements to the left of the first position.
left = 0
Loop through array
The method iterates over the indices of the list using a range based on the list’s length. This explicit index-based loop enables direct access to both the current element and its position.
for i in range(len(nums)):
Compute right sum
Within each iteration, the right-hand sum is derived by subtracting the left accumulator and the current element from the previously computed total. This calculation yields the sum of all elements that lie to the right of the current index.
right = total - left - nums[i]
Check equality and return
A comparison is performed between the left and right sums. If they match, the current index satisfies the pivot condition and is immediately returned as the result.
if left == right:
return i
Update left accumulator
If the pivot condition is not met, the current element is added to the left accumulator, preparing the correct left sum for the next iteration.
left += nums[i]
Return sentinel value
After the loop concludes without finding a matching index, the method returns -1 to indicate the absence of a pivot index.
return -1
Edge Cases Handled
When the input list is empty, the total sum evaluates to zero and the loop body never executes, leading directly to the sentinel return value. This behavior correctly signals that no pivot index exists.
If the list contains a single element, the left sum is zero before the first iteration, and the right sum is computed as total minus left minus the element, which also yields zero. Consequently, the method returns index zero, correctly identifying the sole element as a valid pivot.
Arrays composed entirely of zeros are handled gracefully because both left and right sums remain zero throughout the traversal, causing the first index to be returned as the pivot.
The algorithm accommodates negative numbers without special treatment; the arithmetic operations naturally incorporate sign, allowing the equality check to succeed when appropriate.
Large integer values are processed using Python’s arbitrary-precision arithmetic, ensuring that overflow does not affect correctness.
Performance Optimizations
The solution achieves efficiency by performing a single pass over the input after an initial aggregation of the total sum. By reusing the pre-computed total, it avoids recomputing the right-hand sum from scratch at each step, eliminating the need for nested loops or auxiliary arrays.
Memory usage is minimized because only a few scalar variables-total, left, right, and the loop index-are maintained regardless of input size. No additional data structures are allocated, resulting in constant extra space.
The early return upon locating the first valid pivot index prevents unnecessary processing of the remaining elements, which can be beneficial when a pivot exists near the beginning of a large array.
Overall, the design balances simplicity with optimal traversal characteristics, delivering a solution that scales linearly with the length of the input while maintaining a minimal memory footprint.
ELI5 - Simplified Explanation
Imagine you have a long line of numbered blocks sitting on a table. The goal is to find one special block somewhere in the middle so that all the blocks to its left add up to the same amount as all the blocks to its right.
First, the code adds every single block together to find the total weight. It starts by looking at the very first block on the left side. It sets the left side sum to zero because there are no blocks before the first one.
Then, it starts walking down the line one block at a time. At each step, it figures out the weight of the right side by taking the total weight, subtracting the left side, and also taking away the block it is currently standing on. If the left side and the right side are exactly the same, it has found the perfect spot in the middle, so it shouts out the position of that block. If the sides do not match, it adds the current block to the left side and keeps moving forward to look at the next one. If it reaches the end of the line and still has not found a perfect spot, it says that no such block exists.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||||
| WalkCCC | C++ | Java | Python | ||||||||
| leetcode.ca | C++ | Java | Python | JS | Rust | Go | TS | ||||
| LeetcodeHelp | C++ | Java | Python | ||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||
| Progiez | C++ | Java | Python | ||||||||
| github | BigEggStudy | C# | |||||||||
| black-shadows | C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fengvyi | C++ | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| lzl124631x | C++ | ||||||||||
| qiyuangong | Java | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vthwang | Java | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, Rust, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| fengvyi | C++ | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| lzl124631x | C++ | ||||||||||
| qiyuangong | Java | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vthwang | Java | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 560: Subarray Sum Equals K
- problem 1991: Find the Middle Index in Array
- problem 2219: Maximum Sum Score of Array
- problem 2270: Number of Ways to Split Array
- problem 2574: Left and Right Sum Differences
Solved On The Same Day
- problem 872: Leaf-Similar Trees
- problem 933: Number of Recent Calls
- problem 1207: Unique Number of Occurrences
- problem 1732: Find the Highest Altitude
- problem 2215: Find the Difference of Two Arrays
- problem 328: Odd Even Linked List
- problem 443: String Compression
- problem 649: Dota2 Senate
- problem 735: Asteroid Collision
- problem 875: Koko Eating Bananas
- problem 901: Online Stock Span
- problem 1161: Maximum Level Sum of a Binary Tree
- problem 1268: Search Suggestions System
- problem 1282: Group the People Given the Group Size They Belong To
- problem 1372: Longest ZigZag Path in a Binary Tree
- problem 1448: Count Good Nodes in Binary Tree
- problem 1456: Maximum Number of Vowels in a Substring of Given Length
- problem 1493: Longest Subarray of 1's After Deleting One Element
- problem 1647: Minimum Deletions to Make Character Frequencies Unique
- problem 1657: Determine if Two Strings Are Close
- problem 1926: Nearest Exit from Entrance in Maze
- problem 2095: Delete the Middle Node of a Linked List
- problem 2130: Maximum Twin Sum of a Linked List
- problem 2352: Equal Row and Column Pairs
- problem 2390: Removing Stars From a String
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality