How Mo’s algorithm orders offline range queries

Short answer: Mo’s algorithm answers a batch of range queries offline when a window can grow or shrink by one cell at a known cost. Sort the queries by the block of the left endpoint and, inside a block, by the right endpoint. Move the current window’s ends to the next query, updating the answer at each step. With block length about n/√q the pointer motion is O(n √q) steps. The method is offline. An update that arrives between queries needs a different structure.


What the problem actually asks

Some range answers are easy to adjust and hard to build from scratch. The number of distinct values in a subarray, or the frequency of the mode, changes in a small way when one cell enters or leaves. Asking each query from an empty window would repeat that work from the left end every time. If every query is known in advance, the windows can be visited in an order that makes consecutive windows share a long overlap.

The order is a space-filling compromise. Sorting only by the left endpoint makes the right endpoint jump. Sorting only by the right endpoint makes the left endpoint jump. Blocks freeze the left endpoint inside an interval of length B, and the right endpoint then moves almost monotonically through that group of queries.


What the algorithm guarantees

Assume adding or removing one index updates the maintained answer in O(F) time. With B blocks on the left coordinate, the left pointer moves O(B) per query and the right pointer moves O(n) per block of queries, for a total of O(q B + n · (n/B)) moves up to a constant factor from the usual analysis. The product is minimized at B near n/√q, and the move count is then O(n √q). Multiply by F for the running time. Extra memory is the sorted query list and the window state.

The answers are exact if the add and remove operations are exact inverses. The algorithm does not handle an array write that is interleaved with the queries, unless a three-dimensional extension with update time is added. That extension is a different schedule. Online queries, which must be answered before the next one is known, cannot be sorted this way.


The working steps

  1. Read all q queries. Choose a block length B near n/√q.
  2. Sort the queries by the block index of the left endpoint, and by the right endpoint inside a block. Reversing the right-endpoint order on alternate blocks shortens the right pointer’s return trip.
  3. Start with an empty window. For each query in the sorted order, add or remove cells until the window matches that query, maintaining the answer.
  4. Store the answer beside the query’s original index. Move on.
  5. After the batch, emit the answers in the caller’s order.

The O(n √q · F) bound is for offline queries and an O(F) window step. A prefix sum, a Fenwick tree, or a segment tree answers online range sums without a batch. Mo’s algorithm is the batch order for windows that only know how to move by one cell.


Approaches that look simpler and fail

Approach Why it fails when the queries are sorted by the left endpoint alone
Sort by the left end and let the right end jump Each jump can rescan the array. The block sort exists so the right end travels forward through a group instead of restarting.
Answer each query from an empty window The results are correct and the cost is proportional to the total length of every query. The shared window is the saving.
Apply the order to queries that arrive one at a time The next left endpoint is unknown, so the sort cannot be built. This is an offline algorithm.
Remove a cell with an update that is not the inverse of add The maintained answer drifts. Every removal has to undo the addition of that same value.

Online associative ranges are a segment tree. Static idempotent ranges are a sparse table. Mo’s algorithm is the offline block sort for expandable windows.


A working example

This Python fragment sorts offline range queries by the block of the left end and by the right end inside a block, then slides one window. The queries ask how many distinct values lie in each range. It prints 3 3.

a = [1, 2, 1, 3, 2]
queries = [(0, 3), (2, 4)]  # inclusive
B = 2
order = sorted(range(len(queries)), key=lambda i: (queries[i][0] // B, queries[i][1]))
freq = {}
distinct = 0
cur_l, cur_r = 0, -1
answers = [0] * len(queries)

def add(i):
    global distinct
    freq[a[i]] = freq.get(a[i], 0) + 1
    if freq[a[i]] == 1:
        distinct += 1

def remove(i):
    global distinct
    freq[a[i]] -= 1
    if freq[a[i]] == 0:
        distinct -= 1

for idx in order:
    L, R = queries[idx]
    while cur_r < R:
        cur_r += 1
        add(cur_r)
    while cur_r > R:
        remove(cur_r)
        cur_r -= 1
    while cur_l < L:
        remove(cur_l)
        cur_l += 1
    while cur_l > L:
        cur_l -= 1
        add(cur_l)
    answers[idx] = distinct
assert answers == [3, 3]
print(*answers)

Where it is used

Mo’s algorithm reorders a batch of offline range queries on a static array so the window slides a short distance between answers. It is a competitive-programming technique. A production range query uses a segment tree or a database index, which also handle updates.


When you can drop this algorithm

Drop Mo’s algorithm when a tree answers the query online in logarithmic time. Keep it for offline batches whose answer has a cheap one-cell update and no better closed form.


Why this stays published

We publish this so a search for Mo’s algorithm returns the block sort and the O(n √q) pointer bound. Mo’s algorithm answers an offline batch of range queries by sorting them into blocks and sliding one window, in O(n √q) moves when a move costs constant time.

本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。

Leave a Reply

Your email address will not be published. Required fields are marked *