{"id":120,"date":"2026-11-13T12:31:55","date_gmt":"2026-11-13T04:31:55","guid":{"rendered":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-a-fenwick-tree-sums-a-prefix\/"},"modified":"2026-11-13T21:50:45","modified_gmt":"2026-11-13T13:50:45","slug":"how-a-fenwick-tree-sums-a-prefix","status":"publish","type":"post","link":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-a-fenwick-tree-sums-a-prefix\/","title":{"rendered":"How a Fenwick tree sums a prefix"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Short answer:<\/strong> A <strong>Fenwick tree<\/strong>, or binary indexed tree, stores partial sums so that the prefix sum through index i, and a point update at i, both run in <strong>O(log n)<\/strong>. The index trick is the least significant set bit: i &amp; \u2212i in two&#8217;s complement. That bit names the range of values the node covers. The structure uses n cells, needs no pointers, and does not by itself represent an arbitrary range update plus an arbitrary range query without a second tree or a difference encoding.<\/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 raw array answers a point update in constant time and a prefix sum in linear time. A prefix-sum array answers the sum in constant time and a point update in linear time, because every later prefix changes. A Fenwick tree keeps both operations logarithmic by storing, at index i, the sum of a segment ending at i whose length is the least significant set bit of i.<\/p>\n\n\n<p class=\"wp-block-paragraph\">Walking i down by clearing that bit visits O(log n) segments that partition the prefix. Walking i up by adding that bit visits every segment that contains i, which is the update path.<\/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\">Point add and prefix sum are O(log n). A range sum from l to r is prefix(r) \u2212 prefix(l\u22121). Extra memory is n numbers, usually 1-based so that the bit trick never sees index 0. The tree does not store a search-tree order of arbitrary keys. The indices are 1..n. Coordinate compression is the usual way to feed it sparse or non-integer positions.<\/p>\n\n\n<p class=\"wp-block-paragraph\">Range add together with point query is the difference-array encoding: add v at l and \u2212v at r+1, and a prefix sum is the point value. Range add together with range query needs two Fenwick trees, storing the coefficients of a linear function of the index. A segment tree represents those range operations more directly and uses about twice the memory.<\/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>Allocate a 1-based array T of length n, initially zero.<\/li>\n<li>To add v at index i, while i \u2264 n, add v to T[i] and then add i &amp; \u2212i to i.<\/li>\n<li>To read the prefix sum through i, set s = 0, and while i &gt; 0, add T[i] to s and subtract i &amp; \u2212i from i.<\/li>\n<li>A range sum on [l, r] is prefix(r) \u2212 prefix(l\u22121), with prefix(0) = 0.<\/li>\n<li>Build from an existing array by calling add at each index, which is O(n log n), or by a linear accumulation that fills each cell from its children in index order.<\/li>\n<\/ol>\n\n\n<p class=\"wp-block-paragraph\">The bit trick is for prefix-shaped segments on a 1-based line. It is not a segment tree, and it is not a sum over an arbitrary subset that is not a prefix or a difference of prefixes. Two-dimensional Fenwick trees exist and multiply the logarithm. A sparse dynamic version needs a hash map or an implicit tree and loses the plain array.<\/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 index is zero-based and the bit step is left unchanged<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Start updates at index 0<\/td>\n<td>The least significant bit of 0 is 0, so i += i &amp; \u2212i never moves. The array is 1-based, or the keys are shifted by one.<\/td>\n<\/tr>\n<tr>\n<td>Store the whole prefix in every cell and still jump by the low bit<\/td>\n<td>The cell at i covers only the segment of length i &amp; \u2212i ending at i. A full prefix in every cell is a prefix array, and the jump double-counts.<\/td>\n<\/tr>\n<tr>\n<td>Update only T[i] and not the ancestors<\/td>\n<td>Later prefixes that include i read those ancestors. Skipping the upward walk leaves them stale.<\/td>\n<\/tr>\n<tr>\n<td>Expect a range assign of an interval in one visit<\/td>\n<td>A Fenwick tree of values supports point updates. A range assignment is a segment tree with lazy tags, or a difference encoding if the query shape allows it.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n\n\n<p class=\"wp-block-paragraph\">Arbitrary range updates with lazy propagation belong to a segment tree. A static prefix array is enough when the values never change. The Fenwick tree is the compact structure for point updates and prefix sums.<\/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\">The Bash script and the Python script are 1-based Fenwick trees. An update adds the step <code>i &amp; -i<\/code>. A prefix sum subtracts it. Both print the prefix through index 3 and the total, <code>6 15<\/code>.<\/p>\n\n<pre><code class=\"language-bash\">n=5\nfor ((i=0; i&lt;=n; i++)); do t[i]=0; done\nadd() {\n  local i=$1 d=$2\n  while (( i &lt;= n )); do\n    t[i]=$((t[i]+d))\n    i=$(( i + (i &amp; -i) ))\n  done\n}\nprefix() {\n  local i=$1 s=0\n  while (( i &gt; 0 )); do\n    s=$((s + t[i]))\n    i=$(( i - (i &amp; -i) ))\n  done\n  echo &quot;$s&quot;\n}\nvals=(1 2 3 4 5)\nfor ((i=1; i&lt;=n; i++)); do add &quot;$i&quot; &quot;${vals[i-1]}&quot;; done\necho &quot;$(prefix 3) $(prefix 5)&quot;\n<\/code><\/pre>\n<pre><code class=\"language-python\">class Fenwick:\n    def __init__(self, n):\n        self.t = [0] * (n + 1)\n\n    def add(self, i, delta):\n        while i &lt; len(self.t):\n            self.t[i] += delta\n            i += i &amp; -i\n\n    def prefix(self, i):\n        s = 0\n        while i &gt; 0:\n            s += self.t[i]\n            i -= i &amp; -i\n        return s\n\ntree = Fenwick(5)\nfor i, v in enumerate([1, 2, 3, 4, 5], 1):\n    tree.add(i, v)\nassert tree.prefix(3) == 6 and tree.prefix(5) == 15\nprint(tree.prefix(3), tree.prefix(5))\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 Fenwick tree is the compact array for an online histogram: update one bucket, read a prefix total. Inversion counting and live scoreboards use that shape. A segment tree stores more nodes and answers a wider family of range 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 Fenwick tree when the queries are static. A prefix array answers them in constant time. Drop it when the updates are arbitrary range assignments. Use a segment tree. Keep it for point add and prefix or range sum on a line of indices.<\/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 Fenwick tree returns the least-significant-bit walk and the 1-based index it requires. <strong>A Fenwick tree answers a prefix sum and a point update in O(log n) time by walking indices in steps of their least significant set bit.<\/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 Fenwick tree, or binary indexed tree, stores partial sums so that the prefix sum through index i, and a point update at i, both run in O(log n). The index trick is the least significant set bit: i &amp; \u2212i in two&#8217;s complement. That bit names&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-120","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\/120","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=120"}],"version-history":[{"count":2,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/120\/revisions"}],"predecessor-version":[{"id":519,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/120\/revisions\/519"}],"wp:attachment":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/media?parent=120"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/categories?post=120"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/tags?post=120"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}