Ch. 18 · Data Structures & Algorithms

Prefix Sums for Repeated Range Queries

Prefix Sums for Repeated Range Queries. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readbeginnerupdated Oct 3, 2026

Prefix sums store cumulative totals so a range can be answered by subtraction. Define indexing and empty-prefix conventions explicitly.

Before you start

You should know arrays, loops and basic complexity notation. Start with a small input you can trace by hand. State what each variable means and which invariant is maintained, then use that invariant to explain correctness before discussing performance or writing a more compact solution.

The practical goal is to reason through this situation: With prefix[0] zero, the inclusive range l through r totals prefix[r+1] minus prefix[l]. Read the walkthrough first, then try the interview exercise before opening its answer. The important part is explaining the decision and its consequences, rather than remembering a definition alone.

Step-by-step walkthrough

Step 1: Choose an indexing convention

Prefix[i] represents the first i elements, with prefix[0]=0.

Step 2: Build cumulative totals

Each next entry adds one original element.

Step 3: Subtract matching boundaries

Inclusive l-to-r uses prefix[r+1]-prefix[l].

Worked scenario

With prefix[0] zero, the inclusive range l through r totals prefix[r+1] minus prefix[l].

For [2,5,1], prefixes are [0,2,7,8]. The range from index one through two sums to 8−2=6. Building costs linear time and each static query constant time; changing the middle element makes later prefixes obsolete.

Common mistake

Off-by-one errors mix inclusive and exclusive boundaries.

Verify the behavior

Check single elements, full range, empty-range policy and updated input.

Interview exercise

Support updates as well as queries.

Answer and reasoning

Static prefixes require rebuilding affected values; consider a Fenwick or segment tree for repeated updates.

Continue learning

Compare the scenario with the Data Structures and Algorithms interview questions and test your understanding with the Data Structures and Algorithms MCQs. For terminology and implementation details, consult the reference material.

More in Data Structures & Algorithms

read ✓Data Structures & Algorithms · mid

Bit Manipulation Patterns for Interviews

Set, test and clear bits, exploit XOR properties, and count set bits with the Brian Kernighan trick.

~2 min readread →
read ✓Data Structures & Algorithms · hard

Backtracking and Safe Pruning Rules

Backtracking and Safe Pruning Rules. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readread →
read ✓Data Structures & Algorithms · easy

Big-O Complexity and Input Growth

Big-O Complexity and Input Growth. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readread →
esc