Courses / DSA Patterns for Working Engineers / Chapter 33
Module 10 · Monotonic stacks, prefix sums and range queries · Chapter 33 of 39
Range Queries: Ordered Sets, Fenwick Trees and Segment Trees
Builds on Modified Binary Search: Bounds, Rotations and Searching the Answer, Tree Depth-First Search: Recursion That Returns Answers Upward, Bitwise Manipulation: Masks, XOR and the 32-Bit Trap and Prefix Sums: Range Totals, Counts and Difference Arrays. Next up: State-Space BFS: Fewest Moves Through Puzzle States.
Part 1 · Introduction to range queries
Fixed data and changing data
A ticket counter's live board shows the total sales between any two hours, while sales keep arriving. A prefix array answers such a question in one subtraction, but only if the data never changes.
A range query asks for a summary of the values in a range, such as their total, minimum or count. A structure that supports range queries usually offers a few operations: read a range, change one value (a point update), and sometimes change a whole range at once (a range update). A second family of problems asks about order: what is the largest booked time at or before a given time, or the smallest at or after it. An ordered set answers those.
Everything in the previous chapter assumed the array was fixed. This chapter keeps the questions and lets the data change.
Code blocks follow the convention set out in the first chapter.