Prefix Sums, Difference Arrays & Windows
In short: build a running-total row once, P[i + 1] = P[i] + a[i], and any
range total becomes one subtraction, P[r + 1] − P[l]. The spare P[0] = 0
cell means a range starting at minute 0 needs no special case. The same trick
runs backwards: a difference array turns a wide range update into two
point writes, with one final sweep — itself a prefix sum — turning differences
back into values. Both only work because addition can be undone; min has no
inverse, which is why the rest of this section exists.
![A prefix row P with a spare zero cell; P[1] and P[5] are highlighted and subtracted to total minutes 1..4](/api/assets/dsa/assets/28b8ac86b4736a2f.png)
From this section on you build Quarry, a search-and-storage engine: the kind of program that sits under a dashboard, keeps a log of everything that happened, and answers questions about it fast. Later sections give it an index, a text search and a storage layer. This section gives it an analytics engine.
The raw material is simple. Quarry keeps one number per minute: how many requests arrived, how many errors, how many bytes were written. A day is 1,440 minutes, a month is 43,200, and the dashboard asks the same shape of question over and over:
How many errors between minute
land minuter?
Every lesson in this section answers that question under a harder rule. Here the log never changes after it is written. Next lesson it gets edited. By the end it takes range updates, minimum queries and lives on disk.
The brute force, and what it costs
The obvious answer is a slice and a sum:
Each query reads every minute it covers. One query over a month is 43,200 reads; a dashboard with twenty panels refreshing every few seconds asks thousands of them. That's O(n) per query and O(n·q) in total, and nearly all of it is re-adding numbers that were added a moment ago by the previous query.