Store the sum before every list position so a half-open range is the difference of two boundaries. The extra zero boundary handles empty and origin-starting ranges, while repeated-sum lookup extends the identity to counting.
Recognize it when Many range-sum questions refer to one unchanged sequence.
Checking your account…
Prefix Sum Code Labs
Count Gaps Rather Than Elements
After learning cumulative totals, give each gap in a list a sum: gap zero contains nothing and gap i contains the first i values. A list of n elements has n+1 such boundaries. This representation avoids using a negative index to special-case a range beginning at the origin.
Build the Boundary Identity Once
The first Lab starts with zero and appends the previous sum plus each incoming value. Negative values can make boundaries decrease; nothing requires the cumulative array to be sorted. The invariant describes which elements are included, not how large the total is.
Build Prefix Boundaries
Reference
def build_prefix_aggregates(values):
prefix = [0]
for value in values:
prefix.append(prefix[-1] + value)
return prefix
Practice
Implement build_prefix_aggregates(values). Return length n + 1 with prefix[0] = 0 and prefix[i + 1] including values[i].
Public tests
Keep the empty boundary
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
Build Prefix Boundaries
def build_prefix_aggregates(values):
prefix = [0]
for value in values:
prefix.append(prefix[-1] + value)
return prefix
Subtract the Two Surrounding Gaps
In [left,right), the right boundary contains all values before right and the left boundary contains exactly the unwanted earlier values. Their difference leaves the requested segment. left == right subtracts a boundary from itself and returns zero, while left == 0 uses the explicit empty sum.
Answer Range Sum Queries
Reference
def range_sum_queries(values, queries):
prefix = [0]
for value in values:
prefix.append(prefix[-1] + value)
return [prefix[right] - prefix[left] for left, right in queries]
Practice
Implement range_sum_queries(values, queries). Each query is a valid half-open [left,right] range with 0 <= left <= right <= len(values). Return its sum.
Public tests
Subtract half-open boundaries
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
Answer Range Sum Queries
def range_sum_queries(values, queries):
prefix = [0]
for value in values:
prefix.append(prefix[-1] + value)
return [prefix[right] - prefix[left] for left, right in queries]
Cancel an Interior Range and an Empty Range
Call the existing query Lab on [4, -1, 6] with half-open ranges [1,3), [0,1) and [2,2). The boundaries need not increase.
Step
Executed statement
State
Why
Empty boundary
prefix = [0]
prefix=[0]
The gap before the first value has sum zero.
Consume 4
prefix.append(prefix[-1] + value)
prefix=[0,4]
Boundary 1 includes exactly one value.
Consume -1
prefix.append(prefix[-1] + value)
prefix=[0,4,3]
A negative value decreases the total without changing the identity.
Consume 6
prefix.append(prefix[-1] + value)
prefix=[0,4,3,9]
The fourth entry is the boundary after all three values.
Answer queries
return [prefix[right] - prefix[left] for left, right in queries]
[9-4,4-0,3-3]=[5,4,0]
Each subtraction cancels the prefix outside its half-open range.
To count target-sum subarrays, an earlier prefix must equal current_prefix-target. A frequency map is needed when the same earlier total occurs more than once; a set loses multiplicity. Query earlier frequencies before recording the current prefix so a zero-length self-pair does not enter the count. This is an extension of the cancellation identity, not behavior implemented by these two range-query Labs.
Explain Reuse and Mutation in an Interview
One preprocessing pass gives O(n) construction and O(1) per valid query, with O(n) storage. A rolling fixed window saves that storage for one prescribed scan. If the source list changes, previously built totals become stale: rebuild in O(n), answer one range directly at O(range length), or choose an update-aware tree. Binary Subarrays With Sum(opens in a new tab) adds earlier-prefix frequencies after the boundary basics.
Templates To Memorize
Learn this shape by heart; most problems in this family change only one or two lines of it.
Prefix sums
Range sum = prefix at the end minus prefix at the start.
You need many range sums, or the sum of everything before or after a position.
Trigger words
range sum
sum of nums[i..j]
product except self
all other elements
running total
difference array
def build_prefix(nums):
prefix = [0] * (len(nums) + 1)
for i, num in enumerate(nums):
prefix[i + 1] = prefix[i] + num
return prefix # sum(nums[i:j]) == prefix[j] - prefix[i]
Spot it when
Many 'sum of nums[i..j]' questions.
'Product/sum of all other elements'.
Remember
prefix[i] is the sum of the first i items, so prefix[0] = 0 handles ranges that start at 0.
Build once in O(n), answer each range in O(1).
How problems bend it
Product of all other elements: Build a left-product pass and a right-product pass instead of sums.
2D region sums: prefix[r + 1][c + 1] adds the cell to the sums above and to the left, minus the overlap.
Prefix sum with a hash map
Seed {0: 1}; count running - k, then store running.
You count (or find) subarrays whose sum equals k, and values can be negative so a sliding window does not work.
Trigger words
subarray sum equals k
count subarrays with sum
subarray + negatives
sum divisible by k
binary subarrays with sum
def count_subarrays_with_sum(nums, k):
seen = {0: 1} # prefix sum -> how many times it appeared
running = 0
count = 0
for num in nums:
running += num
count += seen.get(running - k, 0) # earlier prefixes that make a sum of k
seen[running] = seen.get(running, 0) + 1
return count
Spot it when
'Number of subarrays with sum k'.
Negative numbers are allowed.
Remember
A subarray ending here sums to k exactly when an earlier prefix equals running - k.
Start with {0: 1} so a subarray starting at index 0 is counted.
How problems bend it
Longest subarray with sum k: Seed {0: -1}, store only the first index of each prefix sum, and measure i - seen[running - k].
Divisible by k: Use running % k as the key.
Python Version Note
Python 3.11+
Python slices copy their elements; prefix subtraction avoids allocating a new slice for each query.