Sqrt decomposition
Split the array into about √n blocks and store a summary (such as a sum) for each. A range query uses whole blocks in the middle and single elements at the ends: O(√n) per query or update, with very simple code. The sheets this guide follows have no problems for this pattern, so the lesson explains the idea and when to use it.
How to recognise it
- Range queries with updates, where O(√n) is fast enough.
- Operations awkward to fit into a segment tree.
- Offline queries reordered by block (Mo's algorithm).
Blocks
B = ceil(sqrt(n)); block[i / B] += a[i]
query(l, r): add single elements until l reaches a block start,
whole blocks while they fit, then the single elements left
Common mistakes
- Off-by-one at block edges.
- Forgetting to update the block summary on a point update.
Problems
No problems listed for this pattern yet.