Fenwick Tree Range Sums With Point Updates

Maintain prefix sums with index & -index jumps so point updates and range queries cost O(log n) each, and changed entries never force a full rescan.

PythonData Integrity

Code

pythonsnippet
34 lines
class FenwickTree:
    """Prefix sums with point updates in O(log n).

    Positions are 1-based; index 0 is a sentinel.
    """

    def __init__(self, size: int) -> None:
        self.size = size
        self.tree = [0] * (size + 1)

    def add(self, position: int, delta: int) -> None:
        while position <= self.size:
            self.tree[position] += delta
            position += position & -position

    def prefix_sum(self, position: int) -> int:
        total = 0
        while position > 0:
            total += self.tree[position]
            position -= position & -position
        return total

    def range_sum(self, left: int, right: int) -> int:
        return self.prefix_sum(right) - self.prefix_sum(left - 1)


fenwick = FenwickTree(8)
for position, score in enumerate([5, 2, 9, 1, 7], start=1):
    fenwick.add(position, score)

print(fenwick.range_sum(1, 3))  # 5 + 2 + 9 = 16
fenwick.add(3, -4)              # score at position 3 drops 9 -> 5
print(fenwick.range_sum(1, 3))  # recomputed without rescanning values
print(fenwick.prefix_sum(5))    # 5 + 2 + 5 + 1 + 7 = 20

Output

Captured from a sandboxed run of this snippet in the build pipeline.

16
12
20

What unfolds at runtime

The working surface is the class FenwickTree and the functions __init__, add, prefix_sum and range_sum — everything else is wiring.

The cycling part of this snippet is while position <= self.size.

Caveats

  • Zero packages pulled in — the runtime ships every API this code touches.

Putting it to use

Signature: def add(self, position: int, delta: int) -> None

The surface worth importing is add; the helpers around it are private to the snippet.

Core lines

def add(self, position: int, delta: int) -> None:
    while position <= self.size:
        self.tree[position] += delta
        position += position & -position
def __init__(self, size: int) -> None:
    self.size = size
    self.tree = [0] * (size + 1)
def range_sum(self, left: int, right: int) -> int:
    return self.prefix_sum(right) - self.prefix_sum(left - 1)

Interactive Tools for This Topic

FAQ

Are there third-party dependencies?
No. The dependency list is empty; the code stays inside the standard library. The file defines `__init__`, `add`, `prefix_sum` at load time.