Overview
Fenwick Tree, also known as Binary Indexed Tree (BIT), is a space-efficient data structure that supports prefix sum queries and point updates in O(log n) time. It’s particularly useful when you need to frequently update elements and query prefix sums.Time Complexity
- Build: O(n log n)
- Point Update: O(log n)
- Prefix Query: O(log n)
- Range Query: O(log n) (two prefix queries)
Implementation
range_query_fenwick_tree_std.cpp
Custom Node Structure
For more complex operations, you can use custom node structures:Basic Usage
- Prefix Sum
- Range Sum
- Frequency Counter
Advanced Patterns
2D Fenwick Tree
Range Update, Point Query
Use difference array technique:Range Update, Range Query
Use two Fenwick trees:Binary Search on Fenwick Tree
Find the k-th smallest element efficiently:Applications
Inversion Count
Count inversions in array in O(n log n)
Dynamic Median
Maintain median of dynamic dataset
Range Sum Queries
Efficient prefix and range sum calculations
Order Statistics
Find k-th smallest element dynamically
Fenwick vs Segment Tree
| Feature | Fenwick Tree | Segment Tree |
|---|---|---|
| Space | O(n) | O(4n) |
| Implementation | Simpler | More complex |
| Point Update | O(log n) | O(log n) |
| Range Update | Requires tricks | Native support |
| Supported Operations | Must have inverse | Any associative op |
| Cache Performance | Better | Worse |
| Constant Factor | Lower | Higher |
When to use Fenwick Tree:
- Operations have inverses (addition/subtraction)
- Memory is constrained
- Need simpler, faster code
- Dealing with prefix sums or frequency counting
- Need range updates with lazy propagation
- Operations don’t have inverses (min, max, gcd)
- Need to store additional information per node
- Need binary search on tree
Practice Problems
- Range Sum Query - Mutable (LeetCode 307)
- Count of Smaller Numbers After Self (LeetCode 315)
- Dynamic Range Sum Queries (CSES)
- Salary Queries (CSES)
- Inversion Count (SPOJ)
See Also
- Segment Tree - More versatile for complex operations
- Sparse Table - O(1) queries for static arrays