Prefix Sum
Precompute running totals so any range sum is one subtraction.
- active this step
- result
- inside the window
Seed with an empty prefix
seen = {0: 1} lets a subarray that starts at index 0 be counted.
VARIABLES
- x
- -
- running
- 0
- count
- 0
Intuition & complexity
The core mental model, trade-offs, and Big-O cost.
What it is
prefix[i] stores the sum of the first i elements, so the sum of nums[a..b] is prefix[b + 1] − prefix[a].
Why it matters
Many range-sum queries drop from O(n) each to O(1) each after an O(n) setup.
Think of it like this
A car’s odometer: the distance for any stretch is the end reading minus the start reading.
Use it when
- Many range-sum queries on data that doesn’t change
- Counting subarrays with a given sum (with a hash map)
- Inputs with negative numbers, unlike windows
Avoid it when
- The array changes often - use a Fenwick or segment tree
- A single query - summing directly is simpler
Complexity cheatsheet
| Operation | Time | Space |
|---|---|---|
| Build the prefix array | O(n) | O(n) |
| Range-sum query | O(1) | O(1) |
| Count subarrays equal to k (with a map) | O(n) | O(n) |
Often confused with: sliding window - it needs validity that changes monotonically; prefix sums don’t.
How to recognize it
Clues in interview prompts that point straight to this pattern.
- “Count subarrays summing to k” means prefix sums plus a count map
- Negative numbers rule out sliding window, not prefix sums
Mistakes & edge cases
Catch common off-by-one bugs and corner cases before submitting.
Common mistakes
- Forgetting the {0: 1} seed - subarrays starting at index 0 are missed
- Off-by-one errors between prefix[i] and prefix[i + 1]
- Updating seen before counting - with k = 0 it counts empty subarrays
Edge cases to test
- k = 0
- Negative numbers
- A single element equal to k
Knowledge check
Quick check to lock in the intuition.
Why seed the map with {0: 1}?
Practice
Apply what you just watched on real interview problems.