Data Structures · Visualization
Fenwick Tree: Introduction
Fenwick Tree
A Fenwick tree (also called a Binary Indexed Tree, or BIT) is a compact structure that answers prefix-sum queries and supports updates, both in O(log n) time, using just a single array and clever index math based on binary representations. Time: O(log n) for update and prefix-sum query, O(n log n) or O(n) to build. Space: O(n).
Big-O: Update and prefix-sum queries both O(log n).
Fenwick Tree: Introduction
Fenwick TreeA Fenwick tree (also called a Binary Indexed Tree, or BIT) is a compact structure that answers prefix-sum queries and supports updates, both in O(log n) time, using just a single array and clever index math based on binary representations. Compared to a segment tree, it's simpler to code and uses less memory, though it's a bit less flexible (it naturally suits sums/prefix-combinable operations, not arbitrary range min/max as easily).
How Fenwick Tree: Introduction Works
- Create an array (typically 1-indexed) the same size as the input.
- Each position in this array stores the sum of a specific range of original elements, determined by the position's lowest set bit in binary.
- To update or query, jump between positions by repeatedly adding or subtracting the lowest set bit of the current index.
- This binary-jumping trick lets both updates and prefix-sum queries touch only O(log n) positions.
Fenwick Tree: Introduction Worked Example
Input: A Fenwick tree conceptually built over [3, 2, -1, 6, 5]
- Position 1 covers just element 1
- Position 2 covers elements 1-2
- Position 4 covers elements 1-4
- Each position's exact coverage is determined by its lowest set bit
Output: A compact array enabling fast prefix sums and updates
Press ▶ Run to watch it step by step.
# Fenwick tree (BIT): 1-indexed.
# bit[i] stores a range sum ENDING at i.
# lowbit(i) = i & -i tells how far back it reaches.
n = 8
bit = [3, 2, -1, 6, 5]
# example: intro on [3, 2, -1, 6, 5]Fenwick Tree: Introduction Time & Space Complexity
When to Use Fenwick Tree: Introduction
- Efficiently maintaining running totals that change frequently (e.g. inventory counts)
- Counting inversions in an array
- Competitive programming problems needing prefix sums with frequent point updates
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.