Binary Indexed / Fenwick Tree

What is Fenwick Tree ?

Calculating Prefix Sum Problem***

We are given an array a[], and we want to be able to perform two types of operations on it.

  1. Change the value stored at an index i. (point update operation)
  2. Find the sum of a prefix of length k. (range sum query)
Approach-1: Simple
Approach-2: Simple Enhanced
Approach-3: Use Segment Tree
Approach-4: Use Fenwick Tree

Representation:

Updating the Value

Getting Sum

Implementation

class FenwickTree:
    def __init__(self, arr):
        self.n = len(arr)
        self.fenwick_tree = [0]*(self.n+1)

        for i in range(self.n):
            self.update(i, arr[i])
        
    
    def update(self, i, val): 
        i += 1       # index in fenwick_tree[] is 1 more than the index in arr[]

        # Traverse all ancestors and add 'val' 
        while i <= self.n: 
            self.fenwick_tree[i] += val        # Add 'val' to current node of Fenwick Tree 
            i += i & (-i)         # Update index to that of parent in update View
    

    def query(self, i):
        total_sum = 0
        i += 1
    
        # Traverse ancestors of fenwick_tree[index] and the value to sum
        while i > 0:  
            total_sum += self.fenwick_tree[i]      # Add current element of fenwick_tree to sum 
            i -= i & (-i)          # Move index to parent node in getSum View

        return total_sum



print("Fenwick Tree Example:")
arr = [2, 1, 1, 3, 2, 3, 4, 5, 6, 7, 8, 9]
fen_tree = FenwickTree(arr)
print("Sum of elements in arr[0..5] is : {}".format(fen_tree.query(5)))
fen_tree.update(3, 6)
print("Sum of elements in arr[0..5] after update is : {}".format(fen_tree.query(5)))

Output:

Complexity:

2-D Binary Indexed / Fenwick Tree



← Previous: Interval Tree

Next: Splay Tree →