Data Structures

Fenwick Tree (Binary Indexed Tree)

An efficient data structure for calculating prefix sums and performing point updates, offering logarithmic time complexity for both operations.

Fenwick Tree in Python

Here is a Python implementation of a Fenwick Tree (BIT) that supports point updates and prefix sum queries.

class FenwickTree:
    def __init__(self, size):
        self.tree = [0] * (size + 1)

    def update(self, index, delta):
        index += 1
        while index < len(self.tree):
            self.tree[index] += delta
            index += index & -index

    def query(self, index):
        index += 1
        s = 0
        while index > 0:
            s += self.tree[index]
            index -= index & -index
        return s

AI Coach Hint: The core idea of a Fenwick Tree is the bitwise operation `index & -index`, which isolates the last set bit of `index`. This operation is key to navigating the tree structure and achieving the O(log n) complexity.

Related Algorithm Guides

Explore more algorithm interview guides powered by AI coaching

Bst Vs Hash Table Interview Questions
AI-powered interview preparation guide
Avl Tree Interview Questions
AI-powered interview preparation guide
Professional Integrity Interview Examples
AI-powered interview preparation guide
Aws Solutions Architect Interview Questions
AI-powered interview preparation guide