AlgoTales · Roadmap

Mo's algorithm

Advanced · 12 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Mo's algorithm answers many "what is true in this range of the data?" questions by sorting them so that consecutive questions overlap, then sliding the window slightly each time. It saves a lot of repeated work when all questions are known in advance.

Practical use cases

  • Web app: Distinct products in many ranges. An analytics page needs, for 20,000 saved date-ranges of orders, the number of different products sold in each. Recounting from scratch each time is far too slow. Sorting the range questions cleverly and sliding one shared window gives all answers with small adjustments between neighbours.
  • Web app: Batch report for many selected ranges. A finance export asks for statistics on thousands of selected row ranges of a ledger. All questions are in the upload, so they can be reordered. The reordered run finishes in seconds and the results are sent back in the original order. Because neighbours in the new order are close together, the shared window moves only a little between questions.
  • Web app: Popular words in selected chat segments. A moderation tool checks which words repeat in thousands of chosen stretches of a chat log. Sliding one window along the log, with word counts updated one message at a time, avoids recounting every stretch, so the moderation report stays quick.
  • System: Offline batch analytics and tree queries. A reporting system collects all its range questions first and answers them in a smart order. The same idea works on trees by flattening them into a list. The answers are put back in the original order at the end, so the caller never notices the shuffling.

The story: Mira and the Sliding Spotlight

At the school annual day, a row of 100,000 children stood on a long stage, each wearing a coloured scarf. The teacher had a list of questions: "Between child 5 and child 800, how many different scarf colours do you see?"

The slow way is to point the spotlight at child 5, walk to child 800 and count colours. For each question, from scratch. With 100,000 questions, the teacher's legs would give up.

Mira noticed something. The questions were already written on a sheet before the show began. "Why not answer them in a smart order?" If two questions ask about nearly the same part of the stage, move the spotlight just a little, adding or removing a child or two at its edges, instead of starting over.

Sort the questions so the spotlight walks smoothly along the stage in small steps. The total walking shrinks dramatically. This clever reordering is known as Mo's algorithm.

How to spot this problem, and where you need it

You have many range questions on a list that does not change, you know them all in advance, and the answer is hard to combine from pieces, so recounting per question is too slow.

Signs you need it

  • The input contains an array and thousands of queries like "from position L to R, how many distinct..." or "most frequent...".
  • Prefix sums or segment trees cannot combine the answers because things like distinct counts do not add.
  • You can answer all the queries at the end, in any order, as long as the output order is restored.

Where to use it in a project

  • Batch analytics reports over many selected row ranges of orders, logs or ledgers.
  • Offline processing of saved filters or saved date ranges over a large order list.
  • Contest-style problems and tree-path questions that can be flattened into a list first.

The solution

Split the list into blocks of about the square root of its length. Sort the queries by the block their left end falls in, then by their right end. Keep one live window with running counts. For each query, move the left and right edges one step at a time, adding or removing items, until the window matches the query. Save the answer and continue.

Payoff: Before: recounting 100,000 items for each of 100,000 queries. After: about thirty million small window moves in total, seconds of work.

Explain it like I am 8

Imagine a torch beam on a long wall of pictures. For each question you must light up a different section. If you do the questions in a random order, you run back and forth. If you sort them so neighbouring questions are close, you only shuffle the beam a tiny bit each time.

How it works, step by step

  1. Read all queries first (this only works offline, when no updates happen).
  2. Pick a block size near the square root of n (for n = 8, about 3).
  3. Sort queries by the block of their left end, then by their right end.
  4. Keep a current window [L, R] and its answer. For a new query, move L and R one step at a time to the new ends, calling add(i) or remove(i) as elements enter or leave.
  5. Save each answer under the query's original number, and print them in the original order.

The code in four languages

PHP

<?php
// Distinct values in many ranges using Mo's algorithm. Queries are [l, r] (inclusive).
function moDistinct(array $a, array $queries): array {
    $n = count($a);
    $block = max(1, (int) sqrt($n));
    $order = array_keys($queries);
    // Sort query numbers by (block of left end, right end).
    usort($order, function ($x, $y) use ($queries, $block) {
        return [intdiv($queries[$x][0], $block), $queries[$x][1]]
           <=> [intdiv($queries[$y][0], $block), $queries[$y][1]];
    });

    $cnt = array_fill(0, max($a) + 1, 0);
    $distinct = 0; $curL = 0; $curR = -1;
    $add = function (int $i) use (&$cnt, &$distinct, $a) { if ($cnt[$a[$i]]++ === 0) $distinct++; };
    $remove = function (int $i) use (&$cnt, &$distinct, $a) { if (--$cnt[$a[$i]] === 0) $distinct--; };

    $answers = [];
    foreach ($order as $qi) {
        [$l, $r] = $queries[$qi];
        while ($curL > $l) $add(--$curL);      // grow first, then shrink:
        while ($curR < $r) $add(++$curR);      // the window never goes "negative"
        while ($curL < $l) $remove($curL++);
        while ($curR > $r) $remove($curR--);
        $answers[$qi] = $distinct;
    }
    ksort($answers);                            // back to the original question order
    return $answers;
}

$colours = [1, 2, 1, 3, 2, 1, 3, 3];
echo implode(' ', moDistinct($colours, [[0, 2], [5, 7], [1, 4], [3, 6]])), "\n";   // 2 2 3 3

JavaScript

// Distinct values in many ranges using Mo's algorithm. Queries are [l, r] (inclusive).
function moDistinct(a, queries) {
  const block = Math.max(1, Math.floor(Math.sqrt(a.length)));
  // Sort query numbers by (block of left end, right end).
  const order = queries.map((q, i) => i).sort((x, y) =>
    (Math.floor(queries[x][0] / block) - Math.floor(queries[y][0] / block)) ||
    (queries[x][1] - queries[y][1]));

  const cnt = new Array(Math.max(...a) + 1).fill(0);
  let distinct = 0, curL = 0, curR = -1;
  const add = (i) => { if (cnt[a[i]]++ === 0) distinct++; };
  const remove = (i) => { if (--cnt[a[i]] === 0) distinct--; };

  const answers = new Array(queries.length);
  for (const qi of order) {
    const [l, r] = queries[qi];
    while (curL > l) add(--curL);      // grow first, then shrink:
    while (curR < r) add(++curR);      // the window never goes "negative"
    while (curL < l) remove(curL++);
    while (curR > r) remove(curR--);
    answers[qi] = distinct;            // stored under the original question number
  }
  return answers;
}

const colours = [1, 2, 1, 3, 2, 1, 3, 3];
console.log(moDistinct(colours, [[0, 2], [5, 7], [1, 4], [3, 6]]).join(' '));   // 2 2 3 3

Java

import java.util.*;

public class Main {
    static int distinct = 0;                    // how many different values are in the window
    static int[] cnt;

    static void add(int[] a, int i) { if (cnt[a[i]]++ == 0) distinct++; }
    static void remove(int[] a, int i) { if (--cnt[a[i]] == 0) distinct--; }

    // Distinct values in many ranges using Mo's algorithm. Queries are {l, r} (inclusive).
    static int[] moDistinct(int[] a, int[][] queries) {
        int block = Math.max(1, (int) Math.sqrt(a.length));
        // Sort query numbers by (block of left end, right end).
        Integer[] order = new Integer[queries.length];
        for (int i = 0; i < order.length; i++) order[i] = i;
        Arrays.sort(order, (x, y) -> {
            int bx = queries[x][0] / block, by = queries[y][0] / block;
            return bx != by ? Integer.compare(bx, by) : Integer.compare(queries[x][1], queries[y][1]);
        });

        cnt = new int[Arrays.stream(a).max().getAsInt() + 1];
        distinct = 0;
        int curL = 0, curR = -1;

        int[] answers = new int[queries.length];
        for (int qi : order) {
            int l = queries[qi][0], r = queries[qi][1];
            while (curL > l) add(a, --curL);    // grow first, then shrink:
            while (curR < r) add(a, ++curR);    // the window never goes "negative"
            while (curL < l) remove(a, curL++);
            while (curR > r) remove(a, curR--);
            answers[qi] = distinct;             // stored under the original question number
        }
        return answers;
    }

    public static void main(String[] args) {
        int[] colours = {1, 2, 1, 3, 2, 1, 3, 3};
        System.out.println(Arrays.toString(moDistinct(colours, new int[][]{{0, 2}, {5, 7}, {1, 4}, {3, 6}})));   // [2, 2, 3, 3]
    }
}

Go

package main

import (
	"fmt"
	"math"
	"sort"
)

// moDistinct counts distinct values in many ranges using Mo's algorithm. Queries are [l, r] (inclusive).
func moDistinct(a []int, queries [][2]int) []int {
	block := max(1, int(math.Sqrt(float64(len(a)))))
	// Sort query numbers by (block of left end, right end).
	order := make([]int, len(queries))
	for i := range order {
		order[i] = i
	}
	sort.Slice(order, func(x, y int) bool {
		qx, qy := queries[order[x]], queries[order[y]]
		if qx[0]/block != qy[0]/block {
			return qx[0]/block < qy[0]/block
		}
		return qx[1] < qy[1]
	})

	biggest := 0
	for _, v := range a {
		biggest = max(biggest, v)
	}
	cnt := make([]int, biggest+1)
	distinct, curL, curR := 0, 0, -1
	add := func(i int) {
		if cnt[a[i]] == 0 {
			distinct++
		}
		cnt[a[i]]++
	}
	remove := func(i int) {
		cnt[a[i]]--
		if cnt[a[i]] == 0 {
			distinct--
		}
	}

	answers := make([]int, len(queries))
	for _, qi := range order {
		l, r := queries[qi][0], queries[qi][1]
		for curL > l { // grow first, then shrink:
			curL--
			add(curL)
		}
		for curR < r { // the window never goes "negative"
			curR++
			add(curR)
		}
		for curL < l {
			remove(curL)
			curL++
		}
		for curR > r {
			remove(curR)
			curR--
		}
		answers[qi] = distinct // stored under the original question number
	}
	return answers
}

func main() {
	colours := []int{1, 2, 1, 3, 2, 1, 3, 3}
	fmt.Println(moDistinct(colours, [][2]int{{0, 2}, {5, 7}, {1, 4}, {3, 6}})) // [2 2 3 3]
}

Time: O((n + q) · √n) · Extra space: O(n + q). The left end moves only a little inside a block; the right end sweeps once per block, so total moves stay near (n + q) times the block size.

Watch out for

  • Moving the window edges in the wrong order (shrinking before growing) can make the window go "negative" and corrupt the counts.
  • Forgetting to store answers under the original query numbers, so the output order is scrambled.
  • Trying it when updates are mixed with queries. This basic form needs all queries known up front.

Quick check

  1. Why sort the queries?
    • So neighbouring queries need only small window moves
    • To make the output alphabetical
    • To remove duplicates
  2. Mo's algorithm needs the queries...
    • Online, one at a time with no look-ahead
    • Offline, all known in advance
    • Sorted by the user
  3. Window [3,5] must become [4,6]. How many single-step moves?
    • 1
    • 4
    • 2