Binary Indexed Tree

Initializing live version
Download to Desktop

Requires a Wolfram Notebook System

Interact on desktop, mobile and cloud with the free Wolfram Player or other Wolfram Language products.

This Demonstration implements a binary indexed tree (also known as a Fenwick tree), a data structure used mainly to calculate prefix sums (or sums of ranges) in a list efficiently. To compute the sum of the values in a range of the list, move the start and end sliders to specify it. Hover over the entries in the "tree" row to see which elements in the list are contained in that node.


The prefix sum of a list in a certain index is the sum of all of the elements in the list up to and including that index. This algorithm speeds up the computation of prefix sums when the list's items can change; there are more efficient algorithms to compute prefix sums of static lists.

Green nodes represent the values that are added to compute the answer, while red nodes represent the values that are subtracted. Olive-colored nodes are added and subtracted as part of the algorithm, but they do not affect the answer.


Contributed by: Freddy Román (September 2012)
(Mathematica Summer Camp 2012)
Open content licensed under CC BY-NC-SA



Each node stores the sum of the interval in the original list, so by starting at any node and adding up the values of all of the nodes on the way to the root, the sum of the interval (its prefix sum) is computed. With this, to compute the sum of any given interval , it is only necessary to compute .

The tree is "binary indexed" because the parent of each node is obtained by setting to 0 the least significant bit that is 1 from the node's index in base 2.

Queries can be executed with time complexity after a one-time precomputation step that takes . If the array is modified, the tree can be updated in time for each modified position.

Feedback (field required)
Email (field required) Name
Occupation Organization
Note: Your message & contact information may be shared with the author of any specific Demonstration for which you give feedback.