Python 1480.py
class Solution:
def runningSum(self, nums: List[int]) -> List[int]:
have = 0
for n in nums:
have += n
yield have
Difficulty
and has an acceptance rate of about 87% (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 provided implementation defines a class Solution with a method runningSum that produces a running cumulative total for a sequence of integers. The method is written as a generator, returning each intermediate sum on demand rather than constructing a full list up front. This design choice influences both memory usage and the way callers consume the result.
Key Steps
Step 1 - Prepare an accumulator
have = 0
An integer variable have is created and initialized to zero. This variable holds the cumulative total as the input sequence is processed.
Step 2 - Iterate through the input list
for n in nums:
The method walks through each element n of the supplied list nums. The loop works correctly for any iterable length, including the case where nums is empty.
Step 3 - Update the accumulator
have += n
During each iteration the current element n is added to the accumulator have. This single-line update captures the essence of a running sum and automatically accommodates positive, negative, and zero values.
Step 4 - Yield the current sum
yield have
Instead of storing the intermediate results, the method yields the current value of have. The generator protocol allows the caller to retrieve each sum one at a time, which can be especially useful when only a portion of the sequence is needed.
Edge Cases Handled
When the input list is empty, the for loop body never executes, and the generator produces no values. This behavior matches the expectation that a running sum of an empty collection is also empty.
If the list contains a single element, the loop runs once, the accumulator becomes that element, and the generator yields exactly one value, correctly representing the running sum for a one-item sequence.
The accumulator update uses the += operator, which works uniformly for negative numbers, large integers, and zero. Consequently, the method gracefully handles sequences that include any mix of integer signs and magnitudes without additional conditional logic.
Performance Optimizations
The most notable optimization is the use of a generator (yield) rather than building and returning a new list. By emitting each cumulative total as it is computed, the method avoids allocating extra memory proportional to the size of the input. This lazy evaluation is advantageous when the caller consumes the results incrementally or stops early.
The algorithm maintains only a single integer variable (have) in addition to the loop iterator. This minimal state footprint reduces overhead and keeps the execution path tight. The straightforward for loop and in-place addition (+=) avoid unnecessary function calls or temporary objects, contributing to efficient runtime behavior.
ELI5 - Simplified Explanation
Imagine that you have a row of baskets, and each basket holds a different number of shiny marbles. You want to walk along the row and keep a special bag in your hand that gathers up all the marbles you see as you go.
At the very beginning, your bag is empty, so it holds zero marbles. You walk to the first basket and take all the marbles out, adding them to your bag. Now you know how many marbles you have collected so far, so you show that number to your friend.
Next, you walk to the second basket. You take those marbles and drop them into the same bag that already has the first set of marbles inside. You now have a bigger pile, and you show this new total number to your friend again.
You keep doing this for every single basket in the row. Every time you add a new basket of marbles to your bag, you stop for a second to share the new, bigger total with your friend. By the time you get to the very last basket, your bag holds every single marble from the whole row added together.
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++ | Python | Java | TS | |||||||
| WalkCCC | C++ | Python | Java | |||||||||
| leetcode.ca | C++ | Python | Java | C# | Go | PHP | TS | |||||
| Progiez | C++ | Python | Java | |||||||||
| github | BigEggStudy | C# | ||||||||||
| black-shadows | C++ | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JS | |||||||||||
| fartem | Ruby | |||||||||||
| FelixFan1122 | C# | |||||||||||
| fpdjsns | C++ | |||||||||||
| fsq | C++ | |||||||||||
| halfrost | Go | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| qiyuangong | Java | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| vthwang | Java | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, C#, Go, Java, PHP, Python, TypeScript | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JavaScript | |||||||||||
| fartem | Ruby | |||||||||||
| FelixFan1122 | C# | |||||||||||
| fpdjsns | C++ | |||||||||||
| fsq | C++ | |||||||||||
| halfrost | Go | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| qiyuangong | Java | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| vthwang | Java | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| YuriSpiridonov | Python |
Videos
Solved On The Same Day
- problem 1528: Shuffle String
- problem 1773: Count Items Matching a Rule
- problem 1816: Truncate Sentence
- problem 1832: Check if the Sentence Is Pangram
- problem 1859: Sorting the Sentence
- problem 2114: Maximum Number of Words Found in Sentences
- problem 2828: Check if a String Is an Acronym of Words
- problem 1329: Sort the Matrix Diagonally
- problem 1551: Minimum Operations to Make Array Equal
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