Prefix Sums for Range Queries
Find the two prefix values whose difference gives the range sum.
Core Intuition & How It Works
Prefix sums precompute cumulative totals P[i] so the sum of any contiguous range [L, R] is answered in O(1) via P[R + 1] - P[L]. One linear preprocessing pass accelerates arbitrarily many range queries.
In the Byte Sized Algorithms interactive classroom, you can step forward and backward through this algorithm with your keyboard while watching the visual diagram, memory state, and highlighted pseudocode update together.
Time & Space Complexity
| Metric | Complexity |
|---|---|
| Time Complexity | O(n) build, O(1) per query |
| Space Complexity | O(n) |
| Topic Chapter | Chapter 3: Array & String Techniques |
| Difficulty Level | Intermediate |
Key Pattern to Recognize
Use an extra leading zero (P[0] = 0) so every range [L, R] uses the same subtraction formula without special-casing L = 0.
Common Pitfalls & Edge Cases
Off-by-one errors between inclusive and exclusive range indices, or using prefix sums when elements are updated frequently (use Fenwick/Segment Trees instead).
Real-World & Technical Interview Applications
Range sum queries, subarray-sum-equals-K with hash maps, 2D integral images, and financial cumulative metrics.