Hostname: page-component-6766d58669-r8qmj Total loading time: 0 Render date: 2026-05-16T10:30:05.650Z Has data issue: false hasContentIssue false

You could have invented Fenwick trees

Published online by Cambridge University Press:  17 January 2025

BRENT YORGEY*
Affiliation:
Hendrix College, 1600 Washington Ave, Conway, AR 72032, USA (e-mail: yorgey@hendrix.edu)
Rights & Permissions [Opens in a new window]

Abstract

Fenwick trees, also known as binary indexed trees are a clever solution to the problem of maintaining a sequence of values while allowing both updates and range queries in sublinear time. Their implementation is concise and efficient—but also somewhat baffling, consisting largely of nonobvious bitwise operations on indices. We begin with segment trees, a much more straightforward, easy-to-verify, purely functional solution to the problem, and use equational reasoning to explain the implementation of Fenwick trees as an optimized variant, making use of a Haskell EDSL for operations on infinite two’s complement binary numbers.

Information

Type
Functional Pearl
Creative Commons
Creative Common License - CCCreative Common License - BY
This is an Open Access article, distributed under the terms of the Creative Commons Attribution licence (https://creativecommons.org/licenses/by/4.0/), which permits unrestricted re-use, distribution and reproduction, provided the original article is properly cited.
Copyright
© The Author(s), 2025. Published by Cambridge University Press
Figure 0

Fig. 1 Update and range query operations.

Figure 1

Fig. 2 A segment tree.

Figure 2

Fig. 3 Updating a segment tree.

Figure 3

Fig. 4 Performing a range query on a segment tree.

Figure 4

Fig. 5 Performing a range query on a larger segment tree.

Figure 5

Fig. 6 Implementing Fenwick trees with bit tricks.

Figure 6

Fig. 7 Simple segment tree implementation in Haskell.

Figure 7

Fig. 8 Range utilities.

Figure 8

Fig. 9 Indexing a binary tree.

Figure 9

Fig. 10 Inactivating all right children in a segment tree.

Figure 10

Fig. 11 Performing a prefix query on a segment tree.

Figure 11

Fig. 12 Sliding active values down a thinned segment tree.

Figure 12

Fig. 13 Right-leaning drawing of a thinned segment tree, vertically aligning nodes with their storage location.

Figure 13

Fig. 14 Indexing a binary tree with 2 at the root.

Figure 14

Fig. 15 Binary tree labelled with both binary and Fenwick indexing.

Figure 15

Fig. 16 Binary tree labelled with both binary and Fenwick indexing.

Figure 16

Fig. 17 Recurrence for sequence of binary tree indices in a Fenwick array.

Figure 17

Fig. 18 Indexing and interleaving.

Figure 18

Fig. 19 Adding LSB with a sentinel bit + shifts.

Figure 19

Fig. 20 Moving up a segment tree to find successive prefix segments.

Submit a response

Discussions

No Discussions have been published for this article.