{"id":124,"date":"2026-11-13T12:32:02","date_gmt":"2026-11-13T04:32:02","guid":{"rendered":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-a-segment-tree-answers-a-range-query\/"},"modified":"2026-11-13T21:50:50","modified_gmt":"2026-11-13T13:50:50","slug":"how-a-segment-tree-answers-a-range-query","status":"publish","type":"post","link":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-a-segment-tree-answers-a-range-query\/","title":{"rendered":"How a segment tree answers a range query"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Short answer:<\/strong> A <strong>segment tree<\/strong> partitions an array into segments of length a power of two, stored in a heap-indexed array of about <strong>2n<\/strong> cells. A range query visits <strong>O(log n)<\/strong> disjoint nodes whose segments cover the query exactly. A point update walks one root path. A range update that would otherwise touch every leaf stores a <strong>lazy tag<\/strong> on a node and pushes the tag down when a later query needs the children. Both the query and the lazy update are <strong>O(log n)<\/strong>.<\/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\">A Fenwick tree is ideal for prefix sums and awkward for a range minimum, a range assignment, or a query that is not invertible. A segment tree stores the answer for every dyadic segment explicitly. Any query interval is a union of O(log n) of those segments, the same decomposition a binary carry produces.<\/p>\n\n\n<p class=\"wp-block-paragraph\">A range update that rewrote every covered leaf would be linear. The lazy tag says the node already knows the update and the children do not yet. Pushing the tag is deferred until a walk actually enters the node.<\/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\">Build is O(n). Point update, range query, and lazy range update are O(log n) for an associative combine such as sum, minimum, or maximum. Extra memory is about 2n cells, or 4n in the common recursive layout that allocates a full power of two. The combine must be associative. Subtraction as a combine is not a segment-tree operation. The inverse, if one exists, is how a Fenwick tree avoids storing both children.<\/p>\n\n\n<p class=\"wp-block-paragraph\">Lazy propagation is correct only if tags compose. A range-add tag composes by addition. A range-assign tag overwrites a pending add. The push function has to implement that algebra, and a query must push before it reads a child. Forgetting the push returns a stale child next to a correct parent.<\/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>Place the leaves in index order at the bottom of a 1-based heap array, and set each internal node to the combine of its two children. The parent of i is floor(i\/2).<\/li>\n<li>A query on [l, r] walks from the root. A node segment disjoint from [l, r] contributes nothing. A node segment contained in [l, r] contributes its stored value. A partial overlap recurses into both children.<\/li>\n<li>A point update changes a leaf and recomputes ancestors up to the root.<\/li>\n<li>A range update on a node that is fully covered composes a lazy tag and updates that node&#8217;s stored value. It does not enter the children.<\/li>\n<li>Before a walk reads a child, push the parent&#8217;s tag into the children and clear the parent tag.<\/li>\n<\/ol>\n\n\n<p class=\"wp-block-paragraph\">The logarithmic bound is for dyadic ranges on an array, with an associative combine. It is not a Fenwick tree, and it is not a sparse table. A sparse table answers a static idempotent query in constant time and cannot update. A segment tree updates. Persistent and dynamic versions exist and add a logarithm or a memory factor. They are not required for the array case.<\/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 a lazy tag is never pushed<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Store the tag and query a child without pushing<\/td>\n<td>The child still holds the pre-update value. The parent was updated in place, so the two disagree.<\/td>\n<\/tr>\n<tr>\n<td>Combine overlapping node values<\/td>\n<td>The O(log n) cover is a partition of the query. Adding a parent and its child double-counts the child&#8217;s segment.<\/td>\n<\/tr>\n<tr>\n<td>Use a non-associative combine<\/td>\n<td>The value stored at a node depends on having been built from its children in a way that matches any later split of the query. Non-associative operations break that match.<\/td>\n<\/tr>\n<tr>\n<td>Allocate exactly n cells for an internal-node tree<\/td>\n<td>The leaves and the internal nodes both need slots. The usual safe allocation is 4n, or 2n for a careful bottom-up layout.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n\n\n<p class=\"wp-block-paragraph\">Prefix sums with point updates and less memory belong to a Fenwick tree. Static range minimum belongs to a sparse table. The segment tree is the structure that does both updates and arbitrary associative range queries, including lazy range updates.<\/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 is a segment tree for range sums. A point update and a query over a disjoint cover both take a walk of length O(log n). It prints <code>10<\/code>, the sum of indexes 1 through 3 after the update.<\/p>\n\n<pre><code class=\"language-python\">class Seg:\n    def __init__(self, a):\n        self.n = len(a)\n        self.t = [0] * (4 * self.n)\n        self._build(a, 1, 0, self.n - 1)\n\n    def _build(self, a, v, lo, hi):\n        if lo == hi:\n            self.t[v] = a[lo]\n            return\n        mid = (lo + hi) \/\/ 2\n        self._build(a, 2 * v, lo, mid)\n        self._build(a, 2 * v + 1, mid + 1, hi)\n        self.t[v] = self.t[2 * v] + self.t[2 * v + 1]\n\n    def add(self, i, delta, v=1, lo=0, hi=None):\n        if hi is None:\n            hi = self.n - 1\n        if lo == hi:\n            self.t[v] += delta\n            return\n        mid = (lo + hi) \/\/ 2\n        if i &lt;= mid:\n            self.add(i, delta, 2 * v, lo, mid)\n        else:\n            self.add(i, delta, 2 * v + 1, mid + 1, hi)\n        self.t[v] = self.t[2 * v] + self.t[2 * v + 1]\n\n    def query(self, L, R, v=1, lo=0, hi=None):\n        if hi is None:\n            hi = self.n - 1\n        if R &lt; lo or hi &lt; L:\n            return 0\n        if L &lt;= lo and hi &lt;= R:\n            return self.t[v]\n        mid = (lo + hi) \/\/ 2\n        return self.query(L, R, 2 * v, lo, mid) + self.query(L, R, 2 * v + 1, mid + 1, hi)\n\na = [1, 2, 3, 4]\nseg = Seg(a)\nseg.add(2, 1)  # 3 becomes 4\nassert seg.query(1, 3) == 2 + 4 + 4\nprint(seg.query(1, 3))\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\">A segment tree answers a range sum or a range minimum while single positions change, which is the live histogram and the coverage counter. Computational-geometry libraries use the same tree for stabbing queries. A sparse table is the static special case that does not support 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 a segment tree for static prefix sums. An array of prefixes is enough. Drop it for a static idempotent range query if constant time matters. Use a sparse table. Keep the segment tree when the array changes and the query is a range combine.<\/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 a segment tree returns the O(log n) disjoint cover and the lazy tag that must be pushed before a child is read. <strong>A segment tree answers an associative range query and a point or lazy range update in O(log n) time by storing the answer on every dyadic segment.<\/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: A segment tree partitions an array into segments of length a power of two, stored in a heap-indexed array of about 2n cells. A range query visits O(log n) disjoint nodes whose segments cover the query exactly. A point update walks one root path. A range update&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,34],"tags":[],"class_list":["post-124","post","type-post","status-publish","format-standard","hentry","category-algorithms","category-trees"],"_links":{"self":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/124","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=124"}],"version-history":[{"count":2,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/124\/revisions"}],"predecessor-version":[{"id":523,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/124\/revisions\/523"}],"wp:attachment":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/media?parent=124"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/categories?post=124"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/tags?post=124"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}