Python 0303.py
class NumArray:
def __init__(self, nums: List[int]):
self.sums = [ 0 ]
total = 0
for i in nums:
total += i
self.sums.append(total)
def sumRange(self, left: int, right: int) -> int:
return self.sums[right + 1] - self.sums[left]
Difficulty
and has an acceptance rate of about 73% (1+ million submissions).
Typical patterns to solve this problem:
- Array
- Design
- 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 NumArray class that enables fast range-sum queries on a static integer array. The constructor builds a prefix-sum auxiliary structure, and the sumRange method uses this structure to return the sum of elements between two indices in constant time. The design focuses on preprocessing the input once and then serving queries efficiently.
Key Steps
Initialization
When an instance is created, the constructor receives a list of integers. It initializes an internal list called sums with a leading zero. A running total variable, total, accumulates the values of the input list as the loop iterates. After each addition, the current total is appended to sums. This results in sums[i] holding the sum of the first i elements of the original array.
self.sums = [0]
total = 0
for i in nums:
total += i
self.sums.append(total)
Query Execution
The sumRange method receives two indices, left and right, inclusive. It computes the desired range sum by subtracting the prefix sum just before left from the prefix sum at right + 1. Because the prefix array includes an extra leading zero, the subtraction directly yields the sum of the segment [left, right].
return self.sums[right + 1] - self.sums[left]
Edge Cases
The code gracefully handles an empty input list. In that scenario, the loop body never executes, leaving self.sums as [0]. Any call to sumRange would be invalid because there are no valid indices, but the structure itself remains well-formed without raising errors during construction.
When left equals right, the method returns the single element at that position. The subtraction reduces to self.sums[left + 1] - self.sums[left], which equals the element value because the prefix array stores cumulative totals.
If left is zero, the subtraction simplifies to self.sums[right + 1] - self.sums[0]. Since self.sums[0] is defined as zero, the result is simply the prefix sum up to right, correctly representing the sum from the start of the array.
The implementation also tolerates the maximum valid indices because the prefix array is one element longer than the original list. Accessing self.sums[right + 1] is safe for any right that is a valid index in the original array.
Performance Optimizations
The primary optimization lies in the use of a prefix-sum array. By converting the original list into a cumulative representation during construction, the algorithm shifts the work of summing from query time to a one-time preprocessing step. This enables each sumRange call to execute with a single arithmetic operation and two array lookups, eliminating any need for iteration over the queried segment.
Storing the prefix sums in a plain Python list provides fast indexed access, leveraging the underlying C array implementation for O(1) retrieval. The constructor’s loop runs once over the input, building the auxiliary structure with minimal overhead.
Overall, the design achieves rapid query response while keeping the preprocessing cost linear in the size of the input array.
ELI5 - Simplified Explanation
Imagine having a long line of numbered building blocks. Every block has a number written on it. To make adding them up really fast later, this code starts by creating a special list. It walks down the line of blocks one by one and remembers the running total as it goes. It starts with zero and then adds the first block, then adds the next block to that total, and keeps adding until it reaches the end of the line.
Because the code kept track of all those running totals in a new list, it does not have to count every block when someone asks for the sum of a specific section. To find the total of the blocks between a left spot and a right spot, the code looks at the running total stored for the end spot and subtracts the running total that happened just before the starting spot. This allows the computer to find the answer instantly without needing to pick up and count every single block again.
Code Quality
Complexity Analysis
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 | Rust | JS | Go | C | PHP | TS | |||
| LeetcodeHelp | C++ | Python | Java | |||||||||
| MemoryLimitExceeded | C++ | Python | ||||||||||
| Progiez | C++ | Python | Java | |||||||||
| github | aylei | Rust | ||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++ | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| fartem | Ruby | |||||||||||
| fengvyi | C++ | |||||||||||
| fsq | C++ | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | Java | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| pruthvikp | Python | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| zfang399 | C++ | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C, C++, Go, Java, JavaScript, PHP, Python, Rust, TypeScript | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| aylei | Rust | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| fartem | Ruby | |||||||||||
| fengvyi | C++ | |||||||||||
| fsq | C++ | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | Java | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| pruthvikp | Python | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 304: Range Sum Query 2D - Immutable
- problem 307: Range Sum Query - Mutable
Solved On The Same Day
- problem 160: Intersection of Two Linked Lists
- problem 405: Convert a Number to Hexadecimal
- problem 343: Integer Break
- problem 372: Super Pow
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