Problem 303

Abstract / Summary

Given a list of numbers store prefix sums to quickly calculate the sum of any range.

Note

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

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]
10 lines | 302 bytes | submitted August 20, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 73% (1+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Design
  • 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 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 8 | μ = 8.15 | σ = 0.86

Complexity Analysis

not analyzed yet

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++ 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++
46 links | 28 authors | 11 languages

Videos

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

Similar Problems

2 similar problems

Solved On The Same Day

2 easy 2 medium
5 solutions   August 20, 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