advanced pattern
Prefix Sum
Pre-compute cumulative sums to answer range queries in O(1) time. Essential for subarray sum problems.
Time
O(n) build, O(1) query
Space
O(n)
🧠Mental Model
“Running total on a receipt - each line shows cumulative spent so far. To find spending between items 3-7, subtract total at item 2 from total at item 7.”
Verbal cue: Build once, query many times in constant time.
🎯Recognition Triggers
When you see these patterns in a problem, consider this approach:
subarray sumrange sum querycumulativesum between indicescontiguous elements sum
💡Interview Tips
- 1Mention the trade-off: O(n) space for O(1) queries
- 2Prefix sum works for XOR, product (with division), and other associative operations
- 3Can extend to 2D for matrix queries
⚠️Common Mistakes
- ✕Off-by-one errors in prefix indexing
- ✕Forgetting the leading 0 in prefix array
- ✕Not handling negative numbers correctly