Technique
Mo's Algorithm (offline range queries)
Sort range queries by (block of l, r) and move two pointers between consecutive queries, maintaining a window summary with O(1) add/remove.
0/4 solved
Recognise it
The signal
many offline range queries of a non-mergeable statistic (distinct count, pair count by frequency)
1Brute force
Recompute each query from scratch: O(nq).
2The observation
Independent recomputation: neighbouring queries share most of their window.
3Why it works
The maintained window always equals [curL, curR] and its summary is exact.
Reach for it when
- +no updates (or Mo with updates)
Not when
- ×online queries
- ×statistic is mergeable (segment tree / offline BIT is faster)
Practice
- DatingCodeforces2300
- Machine LearningCodeforces2600
- XOR and Favorite NumberCodeforces2200
- Powerful arrayCodeforces2200
Pitfalls
Misconceptions
- !shrinking before expanding can make the window invalid
Go deeper2 combinations · resources
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