Algorithms Playbook
PatternTime O(n) + O(1)/query · Space O(n)7 min read

Prefix sums: answer any range-sum question in O(1)

Precompute running totals once, then get the sum of any subarray with one subtraction. Plus the combo that solves "count subarrays that sum to k".

In short

Build prefix[i] = sum of the first i numbers in O(n). Then the sum of nums[l..r] is `prefix[r+1] − prefix[l]`: O(1) per question instead of O(n).

The idea: running totals

Your bank statement shows a running balance. To know how much you spent between the 10th and the 20th, you don't add up every transaction: you subtract two balances. Prefix sums are that running balance for an array.

Prefix sums: build once, answer any range in O(1)
Range
Speed
0311243145596276

prefix

001·2·3·4·5·6·7·8·
1def build(nums):
2 prefix = [0] * (len(nums) + 1)
3 for i, x in enumerate(nums):
4 prefix[i + 1] = prefix[i] + x
5 return prefix
6
7def range_sum(prefix, l, r): # sum of nums[l..r]
8 return prefix[r + 1] - prefix[l]
prefix[k] will hold the sum of the first k numbers. prefix[0] = 0: the sum of nothing.

Variables

i—
Step 1/10· Built: 0
The trick: everything up to r, minus everything before l. Many "subarray sum" problems become a hash map of prefix sums.

Why the extra 0 at the start

Making prefix one longer, with prefix[0] = 0, means "the sum of nothing". Then ranges that start at index 0 need no special case: sum(0..r) = prefix[r+1] − prefix[0]. Off-by-one errors here are the most common bug, so draw the two rows when in doubt.

The big combo: prefix sums + hash map

Count the subarrays that sum to k (with negative numbers allowed, so sliding window doesn't work). A subarray l..r sums to k when prefix[r+1] − prefix[l] = k, that is, when prefix[l] = prefix[r+1] − k. Walk once, keep a hash map of how many times each prefix sum has appeared, and for each position add the count of current − k.

count, running = 0, 0
seen = {0: 1}          # the empty prefix
for x in nums:
    running += x
    count += seen.get(running - k, 0)
    seen[running] = seen.get(running, 0) + 1

O(n) time instead of O(n²) checking every subarray.

How to recognise it

  • Many questions about sums of ranges on data that doesn't change.
  • Subarray sum equals k, or divisible by k, with negatives allowed.
  • 2D grids: the same idea works with a 2D prefix table for rectangle sums.
  • Variants: prefix products, prefix XOR, prefix counts.

Key takeaways

  • 01prefix[i+1] = prefix[i] + nums[i]; build it once in O(n).
  • 02sum(l..r) = prefix[r+1] − prefix[l], in O(1).
  • 03Start with prefix[0] = 0 to avoid special cases.
  • 04Prefix sums + a hash map count subarrays with sum k in O(n).

Check your understanding

1 of 3

With prefix[0] = 0, what is the sum of nums[l..r]?

Related topics