DSA — Fenwick Tree
What is a Fenwick Tree?
A data structure for efficiently computing prefix sums and updating values.
class FenwickTree:
def __init__(self, n):
self.n = n
self.tree = [0] * (n + 1)
def update(self, i, delta):
while i <= self.n:
self.tree[i] += delta
i += i & (-i)
def query(self, i):
sum = 0
while i > 0:
sum += self.tree[i]
i -= i & (-i)
return sum
Range Sum Query
def range_query(self, l, r):
return self.query(r) - self.query(l - 1)
Build from Array
def build(self, arr):
for i in range(1, len(arr) + 1):
self.update(i, arr[i - 1])
Time Complexity
| Operation | Complexity |
|---|---|
| Update | O(log n) |
| Query | O(log n) |
| Build | O(n log n) |
Applications
- Prefix sum queries
- Range sum queries
- Inversion counting
- Binary indexed operations
Comparison with Segment Tree
| Feature | Fenwick Tree | Segment Tree |
|---|---|---|
| Implementation | Simpler | More complex |
| Space | O(n) | O(n) |
| Constant factor | Smaller | Larger |
| Range updates | Harder | Easier |
Mini Practice
- Implement Fenwick Tree
- Compute prefix sums
- Update and query
- Count inversions
Up Next
Congratulations! You've completed the DSA course. Continue practicing problems on LeetCode and HackerRank.
Related Topics
Frequently Asked Questions about Fenwick Tree
What is Fenwick Tree in DSA?
Fenwick Tree is a fundamental concept in DSA. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Fenwick Tree?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Fenwick Tree.
Why is Fenwick Tree important in DSA?
Fenwick Tree is essential for DSA development. Understanding this concept will help you write better code and solve real-world problems more effectively.