</>
Skip to content
DSA lessons (55/55)

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

OperationComplexity
UpdateO(log n)
QueryO(log n)
BuildO(n log n)

Applications

  • Prefix sum queries
  • Range sum queries
  • Inversion counting
  • Binary indexed operations

Comparison with Segment Tree

FeatureFenwick TreeSegment Tree
ImplementationSimplerMore complex
SpaceO(n)O(n)
Constant factorSmallerLarger
Range updatesHarderEasier

Mini Practice

  1. Implement Fenwick Tree
  2. Compute prefix sums
  3. Update and query
  4. 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.