Skip to main content
Back to the DSA atlas
Range queries Technique Intro

Prefix Sum

Precompute cumulative totals so any range sum becomes one subtraction. Prefix sums are the first serious range-query idea everyone should know.

prefix-sumrange-queryprecomputationarray

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.

Current topic

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.

Range queries Open topic

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.

Range queries Open topic

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 L to R
  • count values inside a range
  • answer subarray aggregates quickly after one preprocessing pass

Doing each query directly costs O(n)O(n). If there are many queries, that is wasteful.

Core idea

Build a cumulative array:

prefix[i]=a[0]+a[1]++a[i1]prefix[i] = a[0] + a[1] + \dots + a[i - 1]

with prefix[0] = 0.

Then any range sum becomes:

sum(L,R)=prefix[R+1]prefix[L]\text{sum}(L, R) = prefix[R + 1] - prefix[L]

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

OperationTimeSpace
BuildO(n)O(n)O(n)O(n)
One range sumO(1)O(1)-

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

ProblemDifficultyKey idea
Range Sum Query - Immutable🟢 EasyPure prefix-sum preprocessing
Subarray Sum Equals K🟡 MediumPrefix sums plus hashing
Product of Array Except Self🟡 MediumPrefix/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.

Related directions

These topics live nearby conceptually, even if they are not direct prerequisites.

More from Range queries

Stay in the same family when you want parallel variations of the same mental model.

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.

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.