High interview relevanceRoadmap: Intermediate
TimeO(n) to build; O(1) per range sum
SpaceO(n)

Why it costs this much

prefix[j] − prefix[i] equals the sum of items i through j − 1, so each query is a single subtraction.

Code

prefix = [0]
for x in nums:
    prefix.append(prefix[-1] + x)     # O(n) to build

def range_sum(i, j):                  # sum of nums[i:j]
    return prefix[j] - prefix[i]      # O(1) per query

Common pitfalls

Updating the array invalidates the table; use a Fenwick tree if updates are frequent. Off-by-one mistakes around the leading 0 are common.

Operation by operation

OperationBestAverageWorstSpace
Prefix sumsO(n) build, O(1) queryO(n) build, O(1) queryO(n) build, O(1) queryO(n)

Prefix sums. The array is not modified between queries. Updates make this O(n) each. Use a Fenwick tree or segment tree for mixed updates and queries.

Keyboard shortcuts

/
Search topics
?
Show this list of shortcuts
r
Open the revision sheet
b
Save or unsave the focused card, or the topic you are reading
l
Mark the focused card, or the topic you are reading, as learned
Space Left arrow Right arrow
In the visualizer: play or pause, step back, step forward
1 to 4 Enter
In the quiz: pick an answer, then go to the next question
Escape
Close this list