ArticleslgStudy

computer science

Fenwick tree

Fenwick tree is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Fenwick tree rather than just read about it. In short: A Fenwick tree or binary indexed tree (BIT) is a data structure that stores an array of values and can efficiently compute prefix sums of the values and update the values. It also supports an efficient rank-search operation for finding the longest prefix whose sum is no more than a specified value.

Fenwick tree — main illustration
Fenwick tree — illustration

Key takeaways

  • Fenwick tree belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Fenwick tree to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Fenwick tree from memory before moving on to harder problems.

Reference excerpt

A Fenwick tree or binary indexed tree (BIT) is a data structure that stores an array of values and can efficiently compute prefix sums of the values and update the values. It also supports an efficient rank-search operation for finding the longest prefix whose sum is no more than a specified value. Its primary use is operating on the cumulative distribution function of a statistical frequency table which is updated often. This structure was proposed by Boris Ryabko in 1989 with a further modification published in 1992. It has subsequently become known under the name Fenwick tree after Peter Fenwick, who described this structure in his 1994 article. A simple array of values is trivial (constant-time) to update but requires O(n) time to compute a prefix sum or search for a prefix length. An array of prefix sums can return a prefix sum in constant time, and search for a prefix length in O(log⁡n) time, but requires O(n) time to update one of the values. A Fenwick tree allows all three operations to be performed in O(log⁡n) time. This is achieved by representing the values as a tree with n+1 nodes where each node in the tree stores the sum of the values from the index of its parent (exclusive) up to the index of the node (inclusive). The tree itself is implicit and can be stored as an array of n values, with the implicit root node omitted from the array. The tree structure allows the operations of value retrieval, value update, prefix sum, and range sum to be performed using only O(log⁡n) node accesses.

Motivation

Given an array of values, it is sometimes desirable to calculate the running total of values up to each index according to some associative binary operation (addition on integers being by far the most common). Fenwick trees provide a method to query the running total at any index, or prefix sum, while allowing changes to the underlying value array and having all further queries reflect those changes. Fenwick trees are particularly designed to implement adaptive arithmetic coding, which maintains counts of each symbol produced and needs to convert those to the cumulative probability of a symbol less than a given symbol. Development of operations it supports were primarily motivated by use in that case.

Description A Fenwick tree is an implicit tree where nodes are consecutively numbered, and parent-child relationships are determined by arithmetic on the node indexes. An important function in this index arithmetic is the least significant set bit. This is the greatest power of two which divides an index i. This is the power of two (1, 2, 4, 8, ...) and not the exponent (0, 1, 2, 3, ...). It can be efficiently computed in two's complement arithmetic as lsb⁡(i)=i&−i (where & denotes bitwise AND). A Fenwick tree is most easily understood using a one-based array A[n] with n values. Using half-open interval syntax, let A(i,j]={A[k]}k=i+1j, the range from i (exclusive) to j (inclusive). The corresponding Fenwick array F[n] stores the range sums F[i]=∑A(i−lsb⁡(i),i]. That is, the sum of lsb⁡(i) values ending with and including A[i]. A fictitious node 0 is used in some descriptions, but is never actually accessed and need not be explicitly stored. lsb⁡(0)=∞, but the value is never actually needed. F[0] may be considered to contain the sum of the empty range A(0,0]={} with value 0. A "Fenwick tree" is actually three implicit trees over the same array: the interrogation tree used for translating indexes to prefix sums, the update tree used for updating elements, and the search tree for translating prefix sums to indexes (rank queries). The first two are normally walked upwards, while the third is usually walked downwards.

The interrogation tree The interrogation tree is defined so that the parent of node i is i−lsb⁡(i)=i&(i−1). For example, the parent of 6 = 1102 is 4 = 1002. Implicit node 0 is the root. Each level k of the tree contains nodes with indices corresponding to sums of k distinct powers of 2 (with k=0 representing an empty sum 0). For example, level k=1 contains nodes 1=20,2=21,4=22,... and level k=2 contains nodes 3=21+20,5=22+20,6=22+21,... Node i has log2(lsb⁡(i)) children (i+1,i+2,i+4,...,i+lsb⁡(i)/2), and lsb⁡(i)−1 total descendants. (These numbers include nodes greater than n, which are omitted and never accessed.) The below diagram shows the structure of a 16-node Fenwick tree's interrogation tree, including the root, so it corresponds to a 15-element array A:

To find the prefix sum A[1]+⋯+A[i], sum the values in i, its parent, its parent's parent, and so on up to (but not including) the root. To compute a range sum A[i]+⋯+A[j], subtract the prefix sums for i−1 and j. This can be optimized by stopping at their first common ancestor. An extreme example is asking for a single entry A[j]. In this case, the common ancestor of j and i=j−1 is j−lsb⁡(j), so start with F[j] and then, as long as i≠j−lsb⁡(j), subtract F[i] and update i := i - lsb(i).

The update tree The update tree is the mirror image of the interrogation tree. The parent of node i is i+lsb⁡(i)=(i|(i−1))+1 (where | denotes bitwise OR). For example, the parent of 6 = 1102 is 8 = 10002. This conceptual tree is infinite, but only the part with indexes up to n is stored or used. Excluding the fictitious nodes with indexes greater than n it will be a forest of disjoint trees, one for each bit set in the binary representation of n. Here, a node's ancestors are all nodes whose range sums include its own. For example, F[6] holds the sum of A(4,6], F[8] holds the sum of A(0,8], and so on. To modify one of the values A[i], add the change to F[i], then i's parent, then its grandparent, and so on, until the index exceeds n.

… excerpt ends here. Continue reading the full article.

Illustrations

Fenwick tree illustration

Worked examples

Example 1 — a first encounter with Fenwick tree

Start with the simplest possible case. Write down what Fenwick tree claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Fenwick tree before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Fenwick tree ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Fenwick tree

In research
Fenwick tree appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Fenwick tree in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Fenwick tree is common in secondary-school and first-year university syllabi. It links to neighbouring topics Russian inventions, Soviet inventions, Trees (data structures), so understanding it makes those chapters shorter.
In everyday life
Look for Fenwick tree outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Fenwick tree” →

How to study Fenwick tree in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Fenwick tree means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Fenwick tree out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Fenwick tree in simple terms?

A Fenwick tree or binary indexed tree (BIT) is a data structure that stores an array of values and can efficiently compute prefix sums of the values and update the values. It also supports an efficient rank-search operation for finding the longest prefix whose sum is no more than a specified value.

Why does Fenwick tree matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Fenwick tree?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Fenwick tree.

Tags

  • Russian inventions
  • Soviet inventions
  • Trees (data structures)

Keep exploring