Sqrt Decomposition
In short: split the log into blocks of about √n minutes and keep one
running summary per block. An edit changes a cell and adjusts its block's
summary — two writes, O(1). A range query reads whole blocks by their summary
and only the two ragged ends cell by cell, for O(√n) total. Small blocks make
the middle expensive and big blocks make the ragged ends expensive, and √n
is the block size where neither dominates.

Last lesson's prefix row had one weakness, and Quarry hits it straight away.
Monitoring agents report late. A minute that already reads 4 errors becomes
6 when a straggler arrives, and that happens hundreds of times a minute. Every
prefix cell after the edit includes the old value, so one edit rewrites up to
n cells.
So there are two extremes, and each is fast at one thing:
| structure | edit one minute | total of l..r |
|---|---|---|
| the raw log | O(1) | O(n) |
| the prefix row | O(n) | O(1) |
When edits and queries are mixed, both extremes cost O(n) per operation on average. This lesson finds the middle, and it is an idea you'll use far beyond range sums: cut the data into blocks and keep one summary per block.
Blocks with summaries
Split the log into blocks of b minutes and store each block's total beside it.
Minute i lives in block i // b.
- Edit minute
i: change the cell, and adjust its block's summary by the same amount. Two writes, O(1). - Total of
l..r: the blocks lying entirely inside the range contribute their summary, one read each. Only the two blocks at the ends are partly covered, and those are read cell by cell.
Here are 16 minutes in four blocks of four, with the four summaries stored after the log. Watch a query over minutes 2..13:
A block that sits wholly inside the range costs one summary read. Only the two ragged ends are read cell by cell.
The last four cells are block summaries. Block A holds 3 + 1 + 4 + 1 = 9, stored once in ΣA. 20 cells. At index 16.
n = 10
b = max(1, int(n ** 0.5))
blocks = (n + b - 1) // b
print(b, blocks)b = 4
print(13 // b, 8 // b, 3 // b)