Courses / DSA Patterns for Working Engineers / Chapter 32
Module 10 · Monotonic stacks, prefix sums and range queries · Chapter 32 of 39
Prefix Sums: Range Totals, Counts and Difference Arrays
Builds on Sliding Windows: Fixed and Variable Ranges Over Sequences, Modified Binary Search: Bounds, Rotations and Searching the Answer and Hash Maps: Lookups, Complements and Pattern Matching. Next up: Range Queries: Ordered Sets, Fenwick Trees and Segment Trees.
Part 1 · Introduction to prefix sums
Totals you compute once
A ticket counter logs sales every hour, and a manager keeps asking for the total between two hours. Adding the hours up for each question repeats work that a single pass could do once.
A prefix sum is a running total. For an array a of n values, pre[i] holds the total of the first i values, so pre[0] is 0 and pre has n + 1 cells. Each cell reuses the one before it: pre[i + 1] = pre[i] + a[i]. Building the array costs one pass, O(n).
The extra cell at the front stands for the empty prefix, and it lets every range use the same formula, including a range that starts at the first value. Wikipedia calls a prefix sum that leaves out the current value, as pre[i] leaves out a[i], an exclusive one, and the version that includes it an inclusive one. This chapter uses the exclusive form.
Code blocks follow the convention set out in the first chapter.