Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Advanced & Niche/Square Root Decomposition

Technique

Mo's Algorithm (offline range queries)

Sort range queries by (block of l, r) and move two pointers between consecutive queries, maintaining a window summary with O(1) add/remove.

Learn firstSquare Root DecompositionSliding WindowOffline Query Processing
0%
mastery
0/4 solved
Practise nextDating
IdeaPracticePitfalls

Recognise it

The signal

many offline range queries of a non-mergeable statistic (distinct count, pair count by frequency)

  1. 1Brute force

    Recompute each query from scratch: O(nq).

  2. 2The observation

    Independent recomputation: neighbouring queries share most of their window.

  3. 3Why it works

    The maintained window always equals [curL, curR] and its summary is exact.

Reach for it when

  • +no updates (or Mo with updates)

Not when

  • ×online queries
  • ×statistic is mergeable (segment tree / offline BIT is faster)

Practice

Next

Dating

0/4 solved
  • DatingCodeforces2300
  • Machine LearningCodeforces2600
  • XOR and Favorite NumberCodeforces2200
  • Powerful arrayCodeforces2200

Pitfalls

Misconceptions

  • !shrinking before expanding can make the window invalid
Go deeper2 combinations · resources

Combinations

  • Mo's Algorithm (offline range queries)+Prefix Sum+Hash Map / Hash Set Lookup

    count subarrays in [l, r] with a pair property, many offline queries

    Mo's Algorithm (offline range queries):
    moves the query window
    Prefix Sum:
    subarray XOR as prefix XOR pair
    Hash Map / Hash Set Lookup:
    frequency counts of prefix values in the window

    XOR and Favorite Number

  • Mo's Algorithm (offline range queries)+Euler Tour / Tree Flattening+Hash Map / Hash Set Lookup

    many offline path queries counting pairs/distinct values on tree paths

    Mo's Algorithm (offline range queries):
    path = range with odd-toggle membership plus the LCA
    Euler Tour / Tree Flattening:
    a 2n entry/exit sequence
    Hash Map / Hash Set Lookup:
    frequency counts by value or gender pair

    Dating

Resources

  • Segment Treecp-algorithms · article
  • Fenwick Treecp-algorithms · article
  • ITMO Segment Tree courseCodeforces EDU · course
  • Efficient and easy segment treesAl.cash · blog
  • Meet in the MiddleUSACO Guide · course
  • Matrix ExponentiationUSACO Guide · course
  • Reservoir samplingWikipedia · article
TodayReviewPatternsProblems