Prefix Sum
Precompute cumulative totals so any range sum becomes one subtraction. Prefix sums are the first serious range-query idea everyone should know.
Interactive visualization
Use the controls to connect the idea to concrete operations before diving into the full write-up.
Base array
idx 0
3
idx 1
1
idx 2
4
idx 3
2
idx 4
5
idx 5
1
Prefix array
p[0]
0
p[1]
3
p[2]
4
p[3]
8
p[4]
10
p[5]
15
p[6]
16
Range sum from two prefix values
sum[1, 4] = prefix[5] - prefix[1] = 15 - 3 = 12.
Family
Range queries
Static and dynamic range aggregates via indexed trees, segment trees, and precomputed tables.
Builds on
Foundational
You can start here without another page first.
Unlocks
5 next topics
Use these follow-ups when you want to apply the current idea in a richer setting.
Learning paths
3
This topic appears in curated progressions so you can keep moving without guessing the next step.
Choose this over that
Choose the lightest range-query tool that still fits
Prefix sums are the baseline. The right upgrade depends on whether updates or richer queries matter.
Prefix Sum
Choose this when: The array is static and range sums are the only thing you need.
Choose something else when: Updates must stay fast or the query is not just a sum.
Fenwick Tree (Binary Indexed Tree)
Choose this when: You need dynamic prefix or range sums and want the smallest implementation that still gives `O(log n)` updates.
Choose something else when: You need more general merge functions, range updates, or richer tree-based extensions.
Segment Tree
Choose this when: Updates and queries are both dynamic, and the aggregate is richer than a plain prefix-style sum.
Choose something else when: The data is static or prefix-style sums are enough.
Problem
You need many range-sum queries on a fixed array:
- sum from
LtoR - count values inside a range
- answer subarray aggregates quickly after one preprocessing pass
Doing each query directly costs . If there are many queries, that is wasteful.
Core idea
Build a cumulative array:
with prefix[0] = 0.
Then any range sum becomes:
That is the whole trick.
Why it matters
Prefix sum is one of the most important “simple but permanent” techniques in DSA.
It shows up before and inside more advanced structures:
- Difference arrays are basically prefix sums run in reverse
- Fenwick trees maintain prefix-style information dynamically
- Segment trees generalize the same range-query goal when updates matter
- Sparse tables are another static precomputation path for different operations
Build
prefix[0] <- 0
for i in 0..n-1:
prefix[i + 1] <- prefix[i] + a[i]
Query
range_sum(L, R):
return prefix[R + 1] - prefix[L]
Complexity
| Operation | Time | Space |
|---|---|---|
| Build | ||
| One range sum | - |
Common uses
- subarray sums
- counting values after converting a predicate into
0/1 - 2D range sums on matrices
- detecting balanced segments after remapping symbols to numbers
Key takeaways
- Prefix sums trade one linear preprocessing pass for constant-time range queries
- They are the cleanest first step into the range-query family
- Many “advanced” structures are really dynamic or generalized versions of this same idea
- If the array never changes and the operation is additive, prefix sum is often the right answer immediately
Practice problems
| Problem | Difficulty | Key idea |
|---|---|---|
| Range Sum Query - Immutable | 🟢 Easy | Pure prefix-sum preprocessing |
| Subarray Sum Equals K | 🟡 Medium | Prefix sums plus hashing |
| Product of Array Except Self | 🟡 Medium | Prefix/suffix accumulation pattern |
Relation to other topics
- Difference array is the update-side counterpart of prefix sums
- Fenwick tree keeps prefix-style queries fast when values change
- Segment tree is heavier but supports richer range queries and updates
What this enables
Once the current idea feels natural, these are the most useful next jumps.
Difference Array
Apply many range updates in O(1) each, then rebuild the final values with one prefix pass. Difference arrays are the update-side twin of prefix sums.
Fenwick Tree (Binary Indexed Tree)
Maintain prefix sums with O(log n) updates and queries using one tiny bit trick. Fenwick trees are the lightest dynamic range-query structure worth knowing.
Mo's Algorithm
Reorder offline range queries so a moving window can answer them with small pointer adjustments instead of rebuilding from scratch.
Segment Tree
Answer range queries and point updates in O(log n). Segment trees are the go-to structure for range sum, range min, and similar problems.
Sparse Table
Answer static range minima, maxima, or gcd queries in O(1) after O(n log n) preprocessing. Sparse tables are pure precomputation power.
Related directions
These topics live nearby conceptually, even if they are not direct prerequisites.
Difference Array
Apply many range updates in O(1) each, then rebuild the final values with one prefix pass. Difference arrays are the update-side twin of prefix sums.
Fenwick Tree (Binary Indexed Tree)
Maintain prefix sums with O(log n) updates and queries using one tiny bit trick. Fenwick trees are the lightest dynamic range-query structure worth knowing.
Mo's Algorithm
Reorder offline range queries so a moving window can answer them with small pointer adjustments instead of rebuilding from scratch.
Segment Tree
Answer range queries and point updates in O(log n). Segment trees are the go-to structure for range sum, range min, and similar problems.
More from Range queries
Stay in the same family when you want parallel variations of the same mental model.
Difference Array
Apply many range updates in O(1) each, then rebuild the final values with one prefix pass. Difference arrays are the update-side twin of prefix sums.
Fenwick Tree (Binary Indexed Tree)
Maintain prefix sums with O(log n) updates and queries using one tiny bit trick. Fenwick trees are the lightest dynamic range-query structure worth knowing.
Li Chao Tree
Maintain dynamic line insertion and min/max queries by storing line candidates in a segment tree over x-values.
Mo's Algorithm
Reorder offline range queries so a moving window can answer them with small pointer adjustments instead of rebuilding from scratch.
Paths that include this topic
Follow one of these sequences if you want a guided next step instead of open-ended browsing.
Range-query toolkit
Start with static prefix tricks, then move into offline, persistent, dynamic, and precomputed range-query structures.
Rooted tree queries
Flatten subtrees, jump through ancestors, and break tree paths into array segments instead of climbing naively.
Offline toolkit
See how reordering queries, rolling back state, and preserving versions can replace online complexity.
From the blog
Pair the atlas with recent writing from the rest of the site when you want a broader engineering perspective alongside the topic graph.