Understanding Fenwick Trees / Binary Indexed Trees

Revision en1, by Malomalomalomalo, 2018-01-23 06:11:10

Im writing this both to help others and test myself so I will try to explain everything at a basic level.

A Fenwick Tree (a.k.a Binary Indexed Tree, or BIT) is a fairly common data structure. BITs are used to efficiently answer certain types of range queries, on ranges from a root to some distant node. They also allow quick updates on individual data points.

An example of a range query would be this: "What is the sum of the numbers indexed from [0,x]?"

An example of an update would be this: "Increase the number indexed by x by v."

A BIT can perform both of these operations in O(log N) time, and takes O(N) memory.

So how does this work?

BITs take advantage of the fact that ranges can be broken down into other ranges, and combined quickly. Adding the numbers 1 through 4 to the numbers 5 through 8 is the same as adding the numbers 1 through 8. Basically, if we can precalculate the range query for a certain subset of ranges, we can quickly combine them to answer any [0,x] range query.

The binary number system helps us here. Every number N can be represented in log N digits in binary. We can use these digits to construct a tree like so:

#### History

Revisions

Rev. Lang. By When Δ Comment
en11 Malomalomalomalo 2018-01-25 02:15:16 0 (published)
en10 Malomalomalomalo 2018-01-25 02:14:30 30 Tiny change: 'plements) &mdash; a = [A inv' -> 'plements) \-a = [A inv'
en9 Malomalomalomalo 2018-01-25 02:11:56 173
en8 Malomalomalomalo 2018-01-24 07:14:16 153 Tiny change: '\{ ++x;\n while' -> '\{ ++x;\n\n while'
en7 Malomalomalomalo 2018-01-24 07:02:04 93 Tiny change: 'roblems.\n<code>\n' -> 'roblems.\n\n<code>\n'
en6 Malomalomalomalo 2018-01-24 06:46:51 10
en5 Malomalomalomalo 2018-01-24 06:45:12 1558
en4 Malomalomalomalo 2018-01-24 06:29:36 1677
en3 Malomalomalomalo 2018-01-24 05:52:10 2118
en2 Malomalomalomalo 2018-01-24 05:34:05 1384
en1 Malomalomalomalo 2018-01-23 06:11:10 1300 Initial revision (saved to drafts)