Range queries: which structure for which job

Video lessonComing soon

1 One book, many questions

The shop from the prefix sums lesson still keeps its book. Each day's profit goes in, in thousands of rupees, and a loss is a negative number:

2031-12133425
Profit on days 0 to 5

The owner now asks two kinds of questions about a stretch of days. A stretch from day l to day r is a range.

  • How much did we make? That is the range's sum. Days 1 to 3 made 3.
  • What was the worst day? That is the range's minimum. For days 1 to 3, it is −1.

Between questions, she sometimes finds a mistake and corrects the book.

A plain loop answers all of these. It walks the range and adds or compares each day. One range can cover all n days, so q questions take up to n × q steps. At n = q = 10⁵, that is around 10¹⁰ steps. At about 10⁸ steps a second, it is far past the time limit, so it gets Time Limit Exceeded (TLE).

This topic has five structures that do better. Each one fits a different job, and the wrong pick is either too slow or gives wrong answers. This lesson is the map: it shows how to pick. The lessons after it open up each structure.

2 Check one: does the array change?

The first check is what happens to the array between questions. There are three cases. Each step below starts from the same book:

Three ways the book can change
2031-12133425
Never: only questions come
  • Never. The array is fixed. We can do work once, before the first question, and answer every question from what we built.
  • Point update. One value changes, and more questions follow. Whatever we built must be cheap to repair.
  • Range update. A whole stretch changes at once, such as a bonus of 1 that was left out on days 1 to 4. Repairing it value by value costs up to n steps per update.

Range updates need one more check: when do the questions come? If every update comes before every question, the difference array from the last lesson applies them all in O(n + q). Then we have a fixed array again. If updates and questions take turns, we need a structure that handles both as they come.

3 Check two: can the answer be undone?

The second check is what each question combines: a sum, a minimum, a maximum, a gcd or an XOR. The prefix sums lesson answered a range sum with one subtraction. We took the total up to day r and subtracted the total before day l. The subtraction removes the days before the range. It works because subtraction undoes addition.

A minimum has no such undo. The steps try the same trick on days 3 to 5:

The prefix trick on days 3 to 5
2031-12133425
nums
002152435485106
Sum: 10 − 4 = 6, which is right

In steps 2 and 3, the second array is the running minimum. Like prefix, its place i covers the days before day i, and its first place is ∞ because no day comes before day 0.

The minimum of days 3 to 5 is 1. The running minimums give −1 and −1, and nothing we do with −1 and −1 gives 1. Once day 2's −1 enters the running minimum, it hides every day after it.

No cleverer formula can fix this. Change day 3 from 1 to 4. The two running minimums are still −1 and −1, but the answer for days 3 to 5 becomes 2. The same two inputs would need two different answers. So a structure for minimums must keep more than running minimums.

Minimums have a different strength: counting a day twice does no harm. Days 3 to 4 have minimum 1 and days 4 to 5 have minimum 2. The smaller one, 1, is the minimum of days 3 to 5, even though day 4 was in both parts. Sums cannot do this. The same two parts add up to 4 + 5 = 9, not 6, because day 4 was counted twice.

A question combinesIts undoOverlap is safe
SumSubtractNo
XORXOR againNo
Min or maxNoneYes
GcdNoneYes

4 The decision table

The two checks together pick the structure:

How the array changesSum or XORMin, max or gcd
NeverPrefix sumsSparse table
One value at a timeFenwick treeSegment tree
Ranges, all before the questionsDifference array, then prefix sumsDifference array, then sparse table
Ranges, between the questionsLazy propagationLazy propagation

A segment tree also works in every cell of the first two rows. It is the most general of the five, but the longest to write. So the table names it only where nothing simpler works.

One more pairing comes up. When ranges change and each question asks for a single value, a Fenwick tree over the difference array answers it. A single value is a prefix sum of the differences.

The next lessons cover each structure:

  • Sparse table. It stores the minimum of every stretch whose length is a power of two. Any range is two such stretches that may overlap, so a question takes O(1).
  • Fenwick tree. It keeps partial sums, so a prefix sum and a point update each take O(log n). A range sum is still one prefix minus another.
  • Coordinate compression. It turns values as large as 10⁹ into their ranks 0, 1, 2 and so on. Then a Fenwick tree can count by value.
  • Segment tree. It splits the array into halves, then halves of halves, and stores each part's answer. Any operation that combines two parts works, min included.
  • Lazy propagation. It lets a segment tree take a range update in O(log n). The change is written on a few large parts and passed down only when a question needs it.

Other tricks exist, such as answering the questions in a sorted order, square-root decomposition and Mo's algorithm. The problems in this topic do not need them.

5 The baseline in code

Every structure in this topic must give the same answers as the plain loop, only faster. So the loop is worth keeping. On small arrays, it checks the fast version. Here is the loop next to the first cell of the table, prefix sums, on the same questions. Each query is a pair [l, r].

On the shop's book with the queries [1, 3], [3, 5] and [0, 5], both return [3, 6, 10]. The loop costs up to n steps per question. The prefix version costs n steps once, then one subtraction per question. Both keep sums in long long, because 10⁵ values of 10⁹ add up to 10¹⁴.

6 What each one costs

At n = 10⁵, log n is about 17. In round numbers, a question and a change cost:

StructureQuestionChange
Plain loopn1
Prefix sums1n, rebuild
Sparse table1n log n, rebuild
Fenwick treelog nlog n
Segment treelog nlog n
Lazy propagationlog nlog n per range
Difference arrayn, at the end1 per range

Building each one and keeping it costs:

StructureBuildMemory
Prefix sumsnn
Sparse tablen log nn log n
Fenwick treen log nn
Segment treen4n
Lazy propagationn8n
Difference arraynonen

With q = 10⁵ operations, the totals spread far apart:

Plain loop10¹⁰Prefix, with changes10¹⁰Fenwick, segment2 × 10⁶Prefix, fixed2 × 10⁵about 1 second
Steps at n = q = 10⁵, on a scale where each mark is ten times the last

The log n structures take around 2 × 10⁶ steps, well inside the limit. Prefix sums and the sparse table answer in O(1), but only while the array holds still. Each change sends them back to a rebuild.

7 Mistakes

  • Prefix sums on a changing array. Each correction needs a rebuild of n steps. With 10⁵ corrections between questions, that is 10¹⁰ steps and TLE.
  • A running minimum for an inner range. On the shop's book, days 3 to 5 give −1 instead of 1, and the submission gets Wrong Answer. A running minimum only answers ranges that start at day 0.
  • A sparse table with changes. One value sits inside about n of its stored stretches. Each change then costs as much as a rebuild.
  • Lazy propagation where a difference array is enough. If every update comes before every question, a difference array takes O(n + q) and about ten lines. Lazy propagation takes several times the code and is easier to get wrong.

8 Picking for real problems

Each problem in this topic fits one cell of the table. For each statement, we first answer the two checks:

ProblemChangesQuestionPick
Range Minimum QueriesNeverMinSparse table
Range Sum Query - MutableOne valueSumFenwick tree
Range Minimum with UpdatesOne valueMinSegment tree
Range Add, Range SumRanges, between questionsSumLazy propagation

Three of these picks need a reason:

  • Range Sum Query - Mutable. A segment tree passes too. The Fenwick tree is shorter, so it is less to get wrong.
  • Range Minimum with Updates. A Fenwick tree answers a range as one prefix minus another. That is the same undo as prefix sums, and min has none.
  • Range Add, Range Sum. A difference array needs every add before the first question. Here sums come between the adds.

Some problems hide the array. It can be a count for each value seen so far, with questions like "how many seen values are smaller than x?". That is a prefix sum over the counts, and each new value is a point update. So the pick is a Fenwick tree, after coordinate compression when values reach 10⁹.

Before writing any structure, write down the two checks: how the array changes between questions, and whether the answer can be undone. The table gives the rest.

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.