Home
DSA Visualizer
Data Structures
Fenwick Tree (Binary Indexed Tree)
Fenwick Tree (Binary Indexed Tree) Visualization
A Fenwick tree (binary indexed tree) is a data structure for efficiently calculating and updating the prefix sums of a table of values. Step through it in the interactive Fenwick Tree (Binary Indexed Tree) visualization below.
1-BASED INDEXING
READY
Values
1
2
3
4
5
6
7
8
Each slot holds the total of a run of values whose length is its own lowest set bit. Query a prefix to watch that low bit get dropped.
Values
Sum first
Add at
Delta
Intuition
Every integer can be represented as a sum of powers of 2 (binary representation). Similarly, a prefix sum can be represented as a sum of non-overlapping sub-ranges. Fenwick Tree cleverly arranges these ranges so that both updates and prefix sum queries take O(log N) time.
Concept
A Fenwick Tree (or Binary Indexed Tree) is an array-based data structure. Each index i stores the sum of a range defined by the least significant bit (LSB) of i.
How Fenwick Tree (Binary Indexed Tree) Works
- Storage:
BIT[i]stores the sum of the range[i - (i&-i) + 1, i]. - Update(i, delta): Add
deltatoBIT[i], then move toi + (i & -i)(next range covering i). - Query(i): Add
BIT[i]to sum, then move toi - (i & -i)(parent range).
Fenwick Tree (Binary Indexed Tree) Visualization, Step by Step
1. Add val to current node.
2. Move to parent: index += index & (-index).
3. Repeat until index exceeds array size.
1. Add current node value to sum.
2. Move to child/predecessor: index -= index & (-index).
3. Repeat until index becomes 0.
When to Use
- Need Prefix Sums with frequent updates.
- Counting inversions in an array.
- Less memory overhead than Segment Tree (O(N) vs O(4N)).
When NOT to Use
- Range Minimum/Maximum Query (possible but complex).
- Complex range updates (lazy propagation is harder than Segment Tree).
How to Identify
Problems involving "Prefix Sums" and "Mutable Arrays". Often used in competitive programming for simpler range query tasks.
Practice it on interview problems
LeetCode problems solved with the Prefix Sum pattern, each with a step-by-step visualizer:
All Prefix Sum problemsApplying for software engineering roles? Free, no sign-up:
AI resume checker: match your resume to the job description
Compare its cost with every other algorithm in the Big O cheat sheet.
