DSAExpertguide

Mo's Algorithm: Offline Range Queries

Master Mo's Algorithm, a powerful technique for solving offline range query problems in O((N+Q) * sqrt(N)) time.

Sachin SarawgiApril 20, 20262 min read2 minute lesson
Recommended Prerequisites
Segment Tree in Java: Implementation and Range Queries

Mo's Algorithm

Mo's Algorithm is a powerful offline technique used to solve range query problems. It is particularly effective when the query results can be updated incrementally as we shift the query boundaries [L, R] to [L', R'].

The Intuition

The idea is to sort the queries in a specific order so that the total movement of the L and R pointers is minimized. By dividing the array into blocks of size sqrt(N), we can process queries in O((N+Q) * sqrt(N)) time.

Java Implementation Strategy

To use Mo's Algorithm:

  1. Divide the array into blocks of size B = sqrt(N).
  2. Sort the queries primarily by the block of their left endpoint L/B, and secondarily by their right endpoint R.
  3. Move the L and R pointers to match each query, adding or removing elements as you go.
import java.util.*;

class Query implements Comparable<Query> {
    int L, R, id, block;
    public Query(int L, int R, int id, int blockSize) {
        this.L = L;
        this.R = R;
        this.id = id;
        this.block = L / blockSize;
    }
    public int compareTo(Query other) {
        if (this.block != other.block) return Integer.compare(this.block, other.block);
        return Integer.compare(this.R, other.R);
    }
}

Why it matters

  • Efficient Range Queries: Handles problems where no easy "inverse operation" (like subtraction for sum queries) exists.
  • Flexibility: Great for frequency counting, distinct elements, or complex range statistics.

Complexity

  • Time: O((N+Q) * sqrt(N)) where N is the array size and Q is the number of queries.
  • Space: O(N + Q) for the array and queries.
📚

Recommended Resources

Designing Data-Intensive ApplicationsBest Seller

The definitive guide to building scalable, reliable distributed systems by Martin Kleppmann.

View on Amazon
Kafka: The Definitive GuideEditor's Pick

Real-time data and stream processing by Confluent engineers.

View on Amazon
Apache Kafka Series on Udemy

Hands-on Kafka course covering producers, consumers, Kafka Streams, and Connect.

View Course

Practical engineering notes

Get the next backend guide in your inbox

One useful note when a new deep dive is published: system design tradeoffs, Java production lessons, Kafka debugging, database patterns, and AI infrastructure.

No spam. Just practical notes you can use at work.

Sachin Sarawgi

Written by

Sachin Sarawgi

Engineering Manager and backend engineer with 10+ years building distributed systems across fintech, enterprise SaaS, and startups. CodeSprintPro is where I write practical guides on system design, Java, Kafka, databases, AI infrastructure, and production reliability.

Keep Learning

Move through the archive without losing the thread.

Related Articles

More deep dives chosen from shared tags, category overlap, and reading difficulty.

More in DSA

Category-based suggestions if you want to stay in the same domain.