{"id":229,"date":"2026-11-13T12:35:16","date_gmt":"2026-11-13T04:35:16","guid":{"rendered":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-mos-algorithm-orders-offline-range-queries\/"},"modified":"2026-11-13T21:53:15","modified_gmt":"2026-11-13T13:53:15","slug":"how-mos-algorithm-orders-offline-range-queries","status":"publish","type":"post","link":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-mos-algorithm-orders-offline-range-queries\/","title":{"rendered":"How Mo&#8217;s algorithm orders offline range queries"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Short answer:<\/strong> <strong>Mo&#8217;s algorithm<\/strong> answers a batch of range queries offline when a window can grow or shrink by one cell at a known cost. Sort the queries by the block of the left endpoint and, inside a block, by the right endpoint. Move the current window&#8217;s ends to the next query, updating the answer at each step. With block length about n\/\u221aq the pointer motion is <strong>O(n \u221aq)<\/strong> steps. The method is offline. An update that arrives between queries needs a different structure.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the problem actually asks<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Some range answers are easy to adjust and hard to build from scratch. The number of distinct values in a subarray, or the frequency of the mode, changes in a small way when one cell enters or leaves. Asking each query from an empty window would repeat that work from the left end every time. If every query is known in advance, the windows can be visited in an order that makes consecutive windows share a long overlap.<\/p>\n\n\n<p class=\"wp-block-paragraph\">The order is a space-filling compromise. Sorting only by the left endpoint makes the right endpoint jump. Sorting only by the right endpoint makes the left endpoint jump. Blocks freeze the left endpoint inside an interval of length B, and the right endpoint then moves almost monotonically through that group of queries.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the algorithm guarantees<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Assume adding or removing one index updates the maintained answer in O(F) time. With B blocks on the left coordinate, the left pointer moves O(B) per query and the right pointer moves O(n) per block of queries, for a total of O(q B + n \u00b7 (n\/B)) moves up to a constant factor from the usual analysis. The product is minimized at B near n\/\u221aq, and the move count is then O(n \u221aq). Multiply by F for the running time. Extra memory is the sorted query list and the window state.<\/p>\n\n\n<p class=\"wp-block-paragraph\">The answers are exact if the add and remove operations are exact inverses. The algorithm does not handle an array write that is interleaved with the queries, unless a three-dimensional extension with update time is added. That extension is a different schedule. Online queries, which must be answered before the next one is known, cannot be sorted this way.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>The working steps<\/strong><\/h4>\n\n<ol class=\"wp-block-list\">\n<li>Read all q queries. Choose a block length B near n\/\u221aq.<\/li>\n<li>Sort the queries by the block index of the left endpoint, and by the right endpoint inside a block. Reversing the right-endpoint order on alternate blocks shortens the right pointer&#8217;s return trip.<\/li>\n<li>Start with an empty window. For each query in the sorted order, add or remove cells until the window matches that query, maintaining the answer.<\/li>\n<li>Store the answer beside the query&#8217;s original index. Move on.<\/li>\n<li>After the batch, emit the answers in the caller&#8217;s order.<\/li>\n<\/ol>\n\n\n<p class=\"wp-block-paragraph\">The O(n \u221aq \u00b7 F) bound is for offline queries and an O(F) window step. A prefix sum, a Fenwick tree, or a segment tree answers online range sums without a batch. Mo&#8217;s algorithm is the batch order for windows that only know how to move by one cell.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Approaches that look simpler and fail<\/strong><\/h4>\n\n<figure class=\"wp-block-table\">\n<table>\n<thead>\n<tr>\n<th>Approach<\/th>\n<th>Why it fails when the queries are sorted by the left endpoint alone<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Sort by the left end and let the right end jump<\/td>\n<td>Each jump can rescan the array. The block sort exists so the right end travels forward through a group instead of restarting.<\/td>\n<\/tr>\n<tr>\n<td>Answer each query from an empty window<\/td>\n<td>The results are correct and the cost is proportional to the total length of every query. The shared window is the saving.<\/td>\n<\/tr>\n<tr>\n<td>Apply the order to queries that arrive one at a time<\/td>\n<td>The next left endpoint is unknown, so the sort cannot be built. This is an offline algorithm.<\/td>\n<\/tr>\n<tr>\n<td>Remove a cell with an update that is not the inverse of add<\/td>\n<td>The maintained answer drifts. Every removal has to undo the addition of that same value.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n\n\n<p class=\"wp-block-paragraph\">Online associative ranges are a segment tree. Static idempotent ranges are a sparse table. Mo&#8217;s algorithm is the offline block sort for expandable windows.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>A working example<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">This Python fragment sorts offline range queries by the block of the left end and by the right end inside a block, then slides one window. The queries ask how many distinct values lie in each range. It prints <code>3 3<\/code>.<\/p>\n\n<pre><code class=\"language-python\">a = [1, 2, 1, 3, 2]\nqueries = [(0, 3), (2, 4)]  # inclusive\nB = 2\norder = sorted(range(len(queries)), key=lambda i: (queries[i][0] \/\/ B, queries[i][1]))\nfreq = {}\ndistinct = 0\ncur_l, cur_r = 0, -1\nanswers = [0] * len(queries)\n\ndef add(i):\n    global distinct\n    freq[a[i]] = freq.get(a[i], 0) + 1\n    if freq[a[i]] == 1:\n        distinct += 1\n\ndef remove(i):\n    global distinct\n    freq[a[i]] -= 1\n    if freq[a[i]] == 0:\n        distinct -= 1\n\nfor idx in order:\n    L, R = queries[idx]\n    while cur_r &lt; R:\n        cur_r += 1\n        add(cur_r)\n    while cur_r &gt; R:\n        remove(cur_r)\n        cur_r -= 1\n    while cur_l &lt; L:\n        remove(cur_l)\n        cur_l += 1\n    while cur_l &gt; L:\n        cur_l -= 1\n        add(cur_l)\n    answers[idx] = distinct\nassert answers == [3, 3]\nprint(*answers)\n<\/code><\/pre>\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Where it is used<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Mo&#8217;s algorithm reorders a batch of offline range queries on a static array so the window slides a short distance between answers. It is a competitive-programming technique. A production range query uses a segment tree or a database index, which also handle updates.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>When you can drop this algorithm<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Drop Mo&#8217;s algorithm when a tree answers the query online in logarithmic time. Keep it for offline batches whose answer has a cheap one-cell update and no better closed form.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Why this stays published<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">We publish this so a search for Mo&#8217;s algorithm returns the block sort and the O(n \u221aq) pointer bound. <strong>Mo&#8217;s algorithm answers an offline batch of range queries by sorting them into blocks and sliding one window, in O(n \u221aq) moves when a move costs constant time.<\/strong><\/p>\n\n\n<p class=\"wp-block-paragraph\">\u672c\u6587\u7531 HoHo \u8207 AI \u5354\u4f5c\u6574\u7406\uff0c\u6700\u5f8c\u66f4\u65b0\u65bc 2026 \u5e74 11 \u6708 13 \u65e5\u3002<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Short answer: Mo&#8217;s algorithm answers a batch of range queries offline when a window can grow or shrink by one cell at a known cost. Sort the queries by the block of the left endpoint and, inside a block, by the right endpoint. Move the current window&#8217;s ends to&hellip;<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[30,62],"tags":[],"class_list":["post-229","post","type-post","status-publish","format-standard","hentry","category-algorithms","category-range-queries"],"_links":{"self":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/229","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/comments?post=229"}],"version-history":[{"count":2,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/229\/revisions"}],"predecessor-version":[{"id":628,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/229\/revisions\/628"}],"wp:attachment":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/media?parent=229"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/categories?post=229"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/tags?post=229"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}