Offline Queries & Mo's Algorithm

Data Structures & Algorithms · Advanced Trees & Queries · Master · 30 min

When every query is known up front, answer them in a clever order: Mo's algorithm slides one window across the array so range questions like 'how many distinct values?' cost O((n + q)·√n) in total.

This lesson is part of TuringPath Pro. See plans.

What you will learn

  • Online vs offline
  • A window that adds and removes one element
  • Mo's order: by block, then by right end
  • The details that bite
  • Another offline trick: sort by right end

More in Advanced Trees & Queries

Previous: Sparse Tables: O(1) Range Minimum · Next: Bitmask DP: DP Over Subsets