Problem 724

Abstract / Summary

Find the index where the sum of numbers on the left equals the sum on the right.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
12 lines | 302 bytes | submitted September 12, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 62% (2+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Prefix Sum
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 9 | μ = 8.81 | σ = 0.77

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
43 links | 27 authors | 10 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

5 similar problems

Solved On The Same Day

26 solutions   September 12, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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