Skip to contentKEEP THE CRAFTTHE SANCTUARY

Prefix Sum

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.

1 practice exercise8 interview problems

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.
Print Output
print(range_sum_queries([4, -1, 6], [[1, 3], [0, 1], [2, 2]])) [5, 4, 0]

Extend an Identity Only with the Needed State

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

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Prefix construction and q direct queriesO(n + q)O(n + q)Building n+1 boundaries costs O(n); each valid query uses two indexed reads and one subtraction.

Space

O(n) prefix storage plus O(q) returned query results.

Assumptions

  • Query bounds satisfy 0 <= left <= right <= n and are exclusive at right. The supplied values remain unchanged during reuse.
  • Python slices copy their elements; prefix subtraction avoids allocating a new slice for each query.

Invariants Worth Saying Aloud

  1. prefix[i] equals the sum of the first i values, with prefix[0] equal to zero.
  2. Subtracting prefix[left] from prefix[right] cancels all contributions outside the half-open [left,right) range.

When To Use Or Avoid Prefix Sum

Use It When

  • Preprocess an immutable list once and answer valid half-open ranges in constant time.
  • Use prefix-frequency lookup for signed target-sum counting when window shrinking is not monotone.

Choose Another Tool When

  • Use a rolling total for one fixed-width pass when storing every boundary is unnecessary.
  • Choose an update-aware structure or rebuild after mutation; a precomputed prefix does not follow later list changes.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Omitting the empty boundary

Without the initial zero, boundary positions no longer equal counts of consumed elements; even a one-value list has the wrong table length.

Prevent it: Seed prefix with [0], preserving n+1 boundary positions.

Avoid

prefix = []
prefix.append(value)

Use instead

prefix = [0]
prefix.append(prefix[-1]+value)

Adding one to an exclusive endpoint

The query [1,3) already names boundary 3. Treating right as inclusive adds one and reads past a length-four prefix table.

Prevent it: Keep the half-open convention and subtract prefix[left] from prefix[right].

Avoid

total = prefix[right+1]-prefix[left]

Use instead

total = prefix[right]-prefix[left]

Reusing totals after input mutation

A prefix built for [2, 3] still sums to 5 after the first source value changes to 7; it is not a live view of the source.

Prevent it: Rebuild prefixes before repeated queries or use an update-aware structure. The shown one-query sum repair costs O(range length).

Avoid

total = prefix[right]-prefix[left]

Use instead

total = sum(values[left:right])

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.