Lesson 12 of 86IntermediatePro Interactive Lesson

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

MetricComplexity
Time ComplexityO(n) build, O(1) per query
Space ComplexityO(n)
Topic ChapterChapter 3: Array & String Techniques
Difficulty LevelIntermediate

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.

Unlock the full course

All 86 lessons across 15 chapters

View pricing

Delete account

This permanently deletes your account and ends any Pro access.