Prefix Sums

Data Structures & Algorithms · Array Techniques · Intermediate · 12 min

Pre-compute running totals once, answer any range-sum question instantly.

Under each number in a row, write the running total so far, starting from 0. To get the sum of any stretch, read two of those totals and subtract, like two odometer readings.

The idea in everyday words

Your car's odometer. To know how far you drove between town A and town B, you don't re-drive the road: you subtract: odometer at B minus odometer at A. A prefix sum is an odometer for a list.

Build the running total

prefix[i] = sum of the first i numbers. Start with 0 to make maths easy.

nums = [3, 1, 4, 1, 5]
prefix = [0]
for x in nums:
    prefix.append(prefix[-1] + x)
print(prefix)     # [0, 3, 4, 8, 9, 14]

Any range sum in O(1)

Sum of nums[l..r] (inclusive) = prefix[r + 1] - prefix[l]. Try other l and r values:

nums = [3, 1, 4, 1, 5]
prefix = [0]
for x in nums:
    prefix.append(prefix[-1] + x)

l, r = 1, 3
print("sum of", nums[l:r + 1], "=", prefix[r + 1] - prefix[l])

Without prefix sums each query is O(n); with them, it's O(1) after O(n) setup.

Level up: prefix sum + hash map

"Count subarrays that sum to k": walk once, keep a map of how many times each running total appeared. If running - k was seen before, those subarrays end here. This combo is a top interview trick.

Step by step

  1. nums:

    [3, 1, 4, 1, 5]

  2. prefix:

    [0, 3, 4, 8, 9, 14]

  3. Query 1..3:

    prefix[4] − prefix[1] = 9 − 3 = 6

  4. Check:

    1 + 4 + 1 = 6 ✓

Code example

def subarrays_sum_k(nums, k):
    count, running, seen = 0, 0, {0: 1}
    for x in nums:
        running += x
        count += seen.get(running - k, 0)
        seen[running] = seen.get(running, 0) + 1
    return count

print(subarrays_sum_k([1, 1, 1], 2))   # 2
print(subarrays_sum_k([1, 2, 3], 3))   # 2

Complexity

  • Time: O(n) build, O(1) per query
  • Space: O(n)

Interview tips

  • 'Range Sum Query', 'Subarray Sum Equals K', 'Product of Array Except Self' use this idea.

  • State the setup cost vs query cost trade-off.

Challenge: Answer Range Queries

Given nums and a list of [l, r] queries (inclusive), return a list with the sum for each query. Build a prefix array first!

Example: range_sums([3, 1, 4, 1, 5], [[0, 2], [1, 3]]) → [8, 6]

Solve it in the browser with tests, hints and an AI coach.

Practice problems

More in Array Techniques

Previous: Sliding Window · Next: Binary Search