Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Algorithms · Data Structures

Blocks of Root-N.

Watch the explainer

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 queries import 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: element return 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?

2. How does a range query use the precomputed block sums?

3. What must a point update do?

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

50282194374682851129133716232120query [2, 13] = 63: 2 + 2 single cells on the left (red), two stored block sums (green), 2 on the right6 operations instead of 12 element reads
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.

IndexWhyActionTotalOps
i = 2inside block 0, not aligned+ a[2] = 881
i = 3inside block 0, not aligned+ a[3] = 192
i = 4block 1 fits in [2, 13]+ sums[1] = 23323
i = 8block 2 fits in [2, 13]+ sums[2] = 21534
i = 12block 3 would overshoot 13+ a[12] = 1545
i = 13inside block 3, not aligned+ a[13] = 9636

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

CaseTimeSpaceWhy
Sqrt decompositionO(√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 queryO(n) query, O(1) updateO(1) extraNothing to maintain. Fine for small n or few queries.
Prefix sumsO(1) query, O(n) updateO(n)Best when the array never changes.
Fenwick treeO(log n) bothO(n)Faster, for sums and similar invertible operations.
Segment treeO(log n) bothO(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
  1. Pick a block size around √n and keep one running sum per block.
  2. An update touches exactly two things: the element, and its block’s sum — adjust by val − old rather than recomputing the block.
  3. 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.
  4. Otherwise add the single element and step forward by one.
  5. The cost argument: at most √n partial elements at each end, plus at most √n whole blocks in between — hence O(√n).
  6. √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.
CPython · WebAssembly

Keep going

▶  Watch it explained

Sqrt Decomposition: Time and Space Complexity, From First Principles

Finished this one? 0 / 99 Algorithms done
NextBits Do the Walking: Fenwick Tree Next on the “Answering a range in log time” ladder · rung 2 of 7

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms