Python 1304.py
class Solution:
def sumZero(self, n: int) -> List[int]:
if n % 2 == 1:
yield 0
for i in range(1, (n // 2) + 1):
yield +i
yield -i
Difficulty
and has an acceptance rate of about 76% (300k+ submissions).
Typical patterns to solve this problem:
- Array
- Math
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 single method sumZero. The method receives an integer n and produces a sequence of n integers whose sum equals zero. Instead of constructing a list explicitly, the method uses Python’s generator semantics (yield) to emit each element on demand. This design enables the caller to iterate over the result without incurring the memory cost of storing the entire collection at once.
Core Logic
The method begins by handling the parity of n. When n is odd, a single zero is emitted to satisfy the requirement of an odd-length sequence that still sums to zero.
if n % 2 == 1:
yield 0
After the optional zero, the method enters a loop that iterates from 1 up to and including n // 2. For each iteration index i, the positive value i and its negative counterpart -i are yielded consecutively.
for i in range(1, (n // 2) + 1):
yield +i
yield -i
Because the loop produces two numbers per iteration, the total count of yielded values matches n. When n is even, the loop alone supplies all required elements; when n is odd, the initial zero plus the pairs from the loop together reach the target length.
Edge Cases Handled
When n equals 1, the parity check triggers the emission of a single zero, and the loop does not execute because n // 2 evaluates to 0. The result is a one-element sequence [0], which correctly satisfies the sum-zero condition.
When n equals 0, the parity condition is false and the loop range becomes range(1, 1), which yields no iterations. Consequently, the generator produces no values, representing an empty sequence as expected for a request of zero elements.
When n is a large even number, the loop runs exactly n // 2 times, each iteration yielding a pair of opposite integers. The presence of both positive and negative counterparts guarantees that the cumulative sum remains zero regardless of the magnitude of n.
Performance Characteristics
The use of yield creates a lazy generator, meaning each integer is computed only when the caller requests it. This approach eliminates the need for an intermediate list, reducing memory consumption to the overhead of the generator object itself and the current value being processed.
The algorithm’s work per element is constant: a simple arithmetic operation to compute i and -i, followed by a yield. No additional data structures are allocated, and there are no nested loops or recursive calls. Consequently, the method scales linearly with the number of elements requested, delivering each value in a predictable and efficient manner.
ELI5 - Simplified Explanation
Imagine you have a magical toy box that needs to be filled with numbers that all add up to zero. To do this, the code looks at how many toys the box needs. If the number happens to be odd, it starts by putting a zero inside because zero never changes the total. Then, it uses a loop to pick pairs of numbers. For every number it chooses, like a one, it also remembers to pick its twin, which is a negative one. When a positive number and its matching negative partner are squished together, they perfectly cancel each other out to become nothing. It keeps doing this until the box is full of these balancing pairs.
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 | Go | Rust | TS | |||||
| Progiez | C++ | Python | Java | ||||||||
| github | BigEggStudy | C# | |||||||||
| black-shadows | C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fpdjsns | Python | ||||||||||
| fsq | C++ | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| muhammadfarhankt | Go | ||||||||||
| qiyuangong | Java | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| fpdjsns | Python | ||||||||||
| fsq | C++ | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| muhammadfarhankt | Go | ||||||||||
| qiyuangong | Java | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| YuriSpiridonov | Python |
Videos
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