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
1def build(nums):2 prefix = [0] * (len(nums) + 1)3 for i, x in enumerate(nums):4 prefix[i + 1] = prefix[i] + x5 return prefix67def range_sum(prefix, l, r): # sum of nums[l..r]8 return prefix[r + 1] - prefix[l]
Variables
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) + 1O(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
Hash maps
A hash map stores key → value pairs and finds any key in O(1) on average. Whenever a loop keeps asking "have I seen this before?", a hash map usually turns O(n²) into O(n).
8 min read →Sliding window
For questions about a contiguous subarray or substring, keep a window: grow it on the right, and shrink it from the left only when it breaks the rule. Each element enters and leaves once: O(n) instead of checking all O(n²) ranges.
9 min read →