Imagine you have a list of a million numbers and you need to answer two kinds of requests that keep arriving in any order: range-sum queries ("what is the sum of elements from index to ?") and point updates ("change element to value "). How fast can you do both?
The naive approach is immediate: keep the raw array. An update costs — just write to one slot. But a query costs — you have to add up every element in the range. The opposite approach, a prefix-sum table, flips the trade: queries drop to , but now every update forces you to recompute the whole table in .
Neither extreme is satisfying when queries and updates arrive equally often. The beautiful insight of sqrt decomposition (also called block decomposition) is that you can split the difference exactly. Partition the array into blocks of size and store the sum of each block alongside the raw elements. Queries walk at most two partial blocks () plus at most whole blocks — totaling . Updates touch one element and rebuild one block sum in . Setting minimizes to exactly : both operations cost .
That perfect balance is not a coincidence. It is a minimax argument: you choose to make the two cost terms equal, and the crossing point is always .
Comments
Loading comments...