Technique
Square Root Decomposition
Split the array into ~sqrt(n) blocks with per-block summaries so updates and queries cost O(sqrt n).
0/2 solved
Recognise it
The signal
operations hard to merge in a segment tree
1Brute force
O(n) per query.
2The observation
Full scans: whole blocks are answered from summaries; only two partial blocks are scanned.
3Why it works
Each block's summary matches its elements after every update.
Reach for it when
- +n, q ~ 1e5 with a 2-5 second limit
- +rebuild periodically (query batching)
Not when
- ×a log-time structure fits (prefer seg-tree)
Practice
- Remainder ProblemCodeforces2100
- Array QueriesCodeforces2000
Pitfalls
Misconceptions
- !block size choice ignored (balance update vs query cost)
Go deepervariants and techniques · 2 combinations · resources
Variants and techniques
Combinations
Mo's Algorithm (offline range queries)+Prefix Sum+Hash Map / Hash Set Lookup
count subarrays in [l, r] with a pair property, many offline queries
- Mo's Algorithm (offline range queries):
- moves the query window
- Prefix Sum:
- subarray XOR as prefix XOR pair
- Hash Map / Hash Set Lookup:
- frequency counts of prefix values in the window
Mo's Algorithm (offline range queries)+Euler Tour / Tree Flattening+Hash Map / Hash Set Lookup
many offline path queries counting pairs/distinct values on tree paths
- Mo's Algorithm (offline range queries):
- path = range with odd-toggle membership plus the LCA
- Euler Tour / Tree Flattening:
- a 2n entry/exit sequence
- Hash Map / Hash Set Lookup:
- frequency counts by value or gender pair