Suppose you have an array of numbers and a list of questions, each asking: "How many distinct values appear between index L and index R?" Answer one question and you're done in linear time. Answer a million of them naively and you'll be scanning billions of elements.
Mo's Algorithm — named after the competitive programmer Mo Tao — is a breathtakingly simple idea: instead of answering queries in the order they arrive, sort them first using a two-pointer block trick. By carefully controlling how much the left and right boundaries move between consecutive queries, the total work drops from to .
No segment tree. No heavy-light decomposition. No persistent structure. Just a clever sort and two pointers that crawl over the array — and for many problems that is all you need.
Comments
Loading comments...