Data Structures19 sections · 729 units
Open in Course

MO's Sorting Order

The magic ordering

Sort queries by:

1.1. Primary: block of left endpoint (l/B\lfloor l/B \rfloor)

2.2. Secondary: right endpoint (rr) Within the same block of ll, right endpoints are sorted. So rr only increases (or decreases after a block change), limiting movement. Across all queries in one ll-block, rr moves at most nn positions total. There are n\sqrt{n} blocks, so total rr movement is O(nn)O(n\sqrt{n}). The ll pointer moves at most B=nB = \sqrt{n} within a block, and there are qq queries, so total ll movement is O(qn)O(q\sqrt{n}). Combined: O((n+q)n)O((n + q)\sqrt{n}).