You have an array and a stream of “sum of range [l, r]” queries. Scanning each range is O(n) per query — too slow when there are many. Sqrt decomposition is the simplest fix: chop the array into √n contiguous blocks and precompute each block’s answer. Now a query grabs the whole blocks fully inside the range in one lookup each, and only scans the leftover elements at the two ends. Whole blocks (about √n) plus two partial ends (each under √n) gives O(√n) per query. Pick a range and watch it touch far fewer cells.
O(√n) per query & update · O(n) space · the simplest sub-linear range structure
block
A contiguous group of about √n elements, with its answer precomputed.
block sum
The precomputed aggregate (here, sum) of a whole block.
whole block
A block entirely inside the query range — used via its precomputed sum, one lookup.
partial end
The leftover elements at the range’s edges — scanned one by one.
sqrt.js — whole blocks plus two ends
Ready
An array of 16, split into 4 blocks of 4, each with a precomputed sum below it. A range query uses whole blocks by their sums and only scans the partial ends. Query range to see how few cells it touches.
–
range sum
–
cells touched
–
naive would
How it works
The magic is choosing the block size to be √n, which balances two opposing costs. A query walks over at most √n whole blocks (each handled in one step via its precomputed sum) plus at most 2·√n loose elements at the two partial ends — so total work is proportional to √n. If blocks were larger, the partial ends would be longer; if smaller, there’d be more blocks to walk. The square root is the sweet spot. Updates are just as cheap: change one element and adjust its single block’s precomputed sum — also O(√n) in the worst case, and often O(1) for a point update.
1
Split into √n blocks
Divide the array into contiguous blocks of about √n elements. For n = 16, that’s 4 blocks of 4.
2
Precompute each block’s answer
Store the sum (or min, max, gcd…) of each whole block. This is the shortcut a query will reuse instead of re-scanning.
3
Query = whole blocks + partial ends
For range [l, r], add the precomputed sum of every block fully inside, and scan only the leftover elements at the two edges. That’s O(√n) work, not O(n).
✓
Update one element and its block
To change an element, update it and adjust just its block’s precomputed sum. All queries stay correct, and the whole structure stays O(√n) per operation.
Query
O(√n)
Update
O(√n)
Space
O(n)
Block size
√n
The code
# sqrt decomposition for range-sum queriesimport math
block = int(math.isqrt(len(a)))
bsum = [sum(a[i:i+block]) for i in range(0, len(a), block)]
def query(l, r): # inclusive [l, r]
total, i = 0, l
while i <= r:
if i % block == 0 and i + block - 1 <= r:
total += bsum[i // block] # whole block: one lookup
i += block
else:
total += a[i]; i += 1 # partial end: elementreturn total
def update(i, val):
bsum[i // block] += val - a[i]; a[i] = val # fix element + its block
Quick check
1. Why is the block size chosen to be √n?
A query costs about (number of whole blocks) + (partial-end elements) = n/block + 2·block. That sum is minimized when block ≈ √n, giving O(√n) per query.
2. How does a range query use the precomputed block sums?
Blocks fully contained in [l, r] contribute their precomputed sum in a single lookup. Only the leftover elements at the two edges (less than a block each) are scanned individually — O(√n) total.
3. What must a point update do?
Updating element i changes exactly one block’s aggregate. Adjust that block’s stored sum by the delta and update the element itself. Everything stays consistent in O(1) for a point update.
FAQ
What is sqrt decomposition?
A technique that splits an array into contiguous blocks of ~√n elements, precomputing an aggregate (sum, min, gcd…) per block. Range queries combine whole-block values with a scan of the partial ends — O(√n) per query and update. It’s the simplest sub-linear range-query structure.
How does it compare to a segment tree?
A segment tree is O(log n) — asymptotically faster than sqrt decomposition’s O(√n) — but sqrt decomposition is far simpler to implement and adapt. Use a segment tree when log n matters or for complex lazy updates; sqrt decomposition is a great low-effort default for moderate sizes.
What is Mo’s algorithm and how does it relate?
Mo’s algorithm answers many offline range queries by sorting them (often by √n block index) and moving the window incrementally. It builds on sqrt-decomposition ideas — the block structure bounds total movement — achieving about O((n + q)·√n) for q queries.
What kinds of queries can sqrt decomposition handle?
Any range query whose per-block answer can be precomputed and combined: sum, min, max, gcd, value counts, and many custom aggregates. Combined with Mo’s algorithm it also handles things like distinct-values-in-range. Its flexibility comes from storing whatever per-block answer you define.
The picture: sixteen cells, four blocks
The array [5, 2, 8, 1, 9, 3, 7, 4, 6, 2, 8, 5, 1, 9, 3, 7] with B = 4. Boxes below are the stored block sums. Green cells are covered by a stored sum; red cells are read one at a time because their block is only partly inside the query.
Worked example, step by step
Take a = [5, 2, 8, 1, 9, 3, 7, 4, 6, 2, 8, 5, 1, 9, 3, 7] with block size 4, so the stored sums are [16, 23, 21, 20]. Query the inclusive range [2, 13] with the page's loop: at index i, if i starts a block and the whole block fits, add its stored sum and jump a block; otherwise add one element and move one step.
Index
Why
Action
Total
Ops
i = 2
inside block 0, not aligned
+ a[2] = 8
8
1
i = 3
inside block 0, not aligned
+ a[3] = 1
9
2
i = 4
block 1 fits in [2, 13]
+ sums[1] = 23
32
3
i = 8
block 2 fits in [2, 13]
+ sums[2] = 21
53
4
i = 12
block 3 would overshoot 13
+ a[12] = 1
54
5
i = 13
inside block 3, not aligned
+ a[13] = 9
63
6
The total is 63, matching a direct sum of the 12 elements (63), in 6 operations. Only 2 blocks were big enough to shortcut; the two ends cost one read per cell. Now update a[5] from 3 to 10: the element changes and sums[1] moves by +7 from 23 to 30, two writes and nothing else. Repeating the query gives 70 (63 + 7), because index 5 sits inside block 1, which the query used whole. A single-block bump is all an update ever has to do.
Complexity and trade-offs
Case
Time
Space
Why
Sqrt decomposition
O(√n) query, O(1) point update (sum)
O(n)
Block size √n balances whole blocks against partial ends. Works for any aggregate you can store per block.
Scan every query
O(n) query, O(1) update
O(1) extra
Nothing to maintain. Fine for small n or few queries.
Prefix sums
O(1) query, O(n) update
O(n)
Best when the array never changes.
Fenwick tree
O(log n) both
O(n)
Faster, for sums and similar invertible operations.
Segment tree
O(log n) both
O(n)
Faster and more general; more code, especially with lazy updates.
Block size controls the balance. On an array of 1,000,000 elements, with 2,000 random ranges (a fixed generator, average range length 249,185), the average operations per query were: block 10: 24,926; block 100: 2,590; block 1,000: 1,227; block 10,000: 9,789; block 100,000: 84,337. The minimum is near block 1,000 (√1,000,000), where a query cost 1,227 operations against 249,185 for a scan. Too small and you walk thousands of blocks; too large and the loose ends dominate. The trees win asymptotically, but this version is a short loop with no pointers, which is often enough.
Common mistakes
Dropping the last partial block
With n = 10 and B = 3 the blocks are 3, 3, 3 and 1. Building only n // B = 3 sums and answering from them gives 45 for the whole-array sum of 1..10, against the true 55: element 10 sits in the fourth, short block (with all four sums: 55). Use ceil(n / B) blocks.
Forgetting to update the block sum
Set a[5] = 10 in the 16-element example but leave sums alone and the query for [2, 13] returns 63, not 70. The element changed and the shortcut still remembers the old value.
Assigning a block sum instead of adjusting it
Writing sums[b] = newValue instead of sums[b] += newValue − oldValue replaces a whole block's total with one element. Doing this for a[5] gives 50 for the same query. The correct update is a delta.
Using the sum update for min or max
A delta works because a sum is invertible; a minimum is not. Raise a[3] from 1 to 9 and the stored block-0 minimum is still 1, so the minimum over indices 0–7 comes back as 1 when the real answer is 2. Recompute the block (O(B)) after any update.
Off-by-one at the block edge
The test i + B − 1 <= r asks whether the block's last index fits. Writing i + B <= r is still correct but refuses to use a block that ends exactly at r, so [4, 7] reads 4 cells instead of 1 stored sum. Writing < r where you meant <= drops the last element.
Where this shows up
Operations a tree cannot store
A per-block summary can be any structure: a sorted copy of the block, a frequency table, a bitset. That makes questions like "how many values in this range are below x" workable without a tree designed for them.
Rebuild-every-so-often designs
Keep a static fast structure plus a small buffer of recent changes, and merge the buffer once it reaches about √n entries. Reads pay for the buffer; rebuilds are amortised over √n changes.
Offline range queries
Sorting queries by the block their left end falls in, then sweeping the right end, is the idea behind Mo's algorithm, which answers many queries without any per-block data at all.
Bulk range updates
Attach a pending "add x to everything" tag to each block, apply it lazily, and an update to a long range touches whole blocks by tag and only the two ends by element.
SOLVE IT YOURSELF
Solve it: range queries with no tree at all
A segment tree is O(log n) but fiddly. Chop the array into √n blocks and you get O(√n) with about ten lines — often fast enough, and far harder to get wrong. Python or TypeScript.
YOUR TASK
Implement a √-decomposition over an array: precompute a sum per block, support update(i, val), and answer range_sum(lo, hi) over an inclusive range.
HINTS — 6 IDEAS
Pick a block size around √n and keep one running sum per block.
An update touches exactly two things: the element, and its block’s sum — adjust by val − old rather than recomputing the block.
A query walks from lo to hi. When you are at a block boundary and the whole block fits inside the range, take the precomputed sum and jump a whole block.
Otherwise add the single element and step forward by one.
The cost argument: at most √n partial elements at each end, plus at most √n whole blocks in between — hence O(√n).
√n is the optimum precisely because it balances those two halves: smaller blocks mean more blocks to skip, larger blocks mean more leftovers to walk.