Skip to contentKEEP THE CRAFTTHE SANCTUARY

Fenwick Tree

A Fenwick tree caches prefix blocks in one-based slots and moves between owners using the lowest set bit. Convert public indices once, distinguish additions from assignments, and derive an inclusive range by subtracting the prefix before its left endpoint.

1 practice exercise2 interview problems

Recognize it when Point additions and repeated prefix/range sums dominate.

Checking your account…

Fenwick Tree Code Labs

Each Index Owns a Suffix Block

Fenwick trees use a one-based array. Slot i owns the suffix block ending at i whose length is i & -i. For example, slot 6 owns positions 5 through 6, while slot 8 owns positions 1 through 8. These overlapping blocks let a prefix decompose into only O(log n) pieces.

Map Fenwick Block Ownership

Reference
def fenwick_block_ranges(n):
    return [[index - (index & -index) + 1, index] for index in range(1, n + 1)]
Practice

Implement fenwick_block_ranges(n). Return [left, right] one-based inclusive ranges owned by Fenwick slots 1 through n. n is a nonnegative integer.

Public tests

  • Map lowbit blocks

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Map Fenwick Block Ownership

def fenwick_block_ranges(n):
    return [[index - (index & -index) + 1, index] for index in range(1, n + 1)]

Move with the Lowest Set Bit

lowbit = i & -i encodes both directions. A prefix query subtracts lowbit to remove the block it just consumed. A point update adds lowbit to visit every larger block containing that position. Keep public indexes zero-based if the prompt uses them, but convert once at the boundary.

Update and Query Prefixes

The actual Lab builds its initial state by calling add once per value, which costs O(n log n); it does not use a specialized linear Fenwick build. A range sum [left, right] is prefix(right) - prefix(left - 1). The left - 1 boundary is essential; prefix(-1) should contribute zero. A query removes one set bit per step. An update jumps to the next larger block owner; adding lowbit may change several bits, but still takes at most O(log n) steps. Public add index -1 is invalid because it converts to internal zero, whose lowbit is zero and cannot advance. The empty-prefix exception applies to queries only.

Trace Fenwick-Tree Prefixes

Reference
def fenwick_tree_trace(values, operations):
    tree = [0] * (len(values) + 1)
    def add(index, delta):
        index += 1
        while index < len(tree):
            tree[index] += delta
            index += index & -index
    def prefix(index):
        index += 1
        total = 0
        while index > 0:
            total += tree[index]
            index -= index & -index
        return total
    for index, value in enumerate(values):
        add(index, value)
    results = []
    for operation in operations:
        if operation[0] == "prefix":
            results.append(prefix(operation[1]))
        elif operation[0] == "add":
            add(operation[1], operation[2])
        elif operation[0] == "range":
            results.append(prefix(operation[2]) - prefix(operation[1] - 1))
    return results
Practice

Implement fenwick_tree_trace(values, operations). Operations are ["prefix", index], ["add", index, delta], or ["range", left, right], with inclusive indexes. Return one number for each prefix or range query and do not mutate values. add requires 0 <= index < len(values); prefix allows -1 for the empty prefix or a valid value index; range requires 0 <= left <= right < len(values). An empty values list accepts no add/range operations.

Public tests

  • Verify Trace Fenwick-Tree Prefixes behavior

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Trace Fenwick-Tree Prefixes

def fenwick_tree_trace(values, operations):
    tree = [0] * (len(values) + 1)
    def add(index, delta):
        index += 1
        while index < len(tree):
            tree[index] += delta
            index += index & -index
    def prefix(index):
        index += 1
        total = 0
        while index > 0:
            total += tree[index]
            index -= index & -index
        return total
    for index, value in enumerate(values):
        add(index, value)
    results = []
    for operation in operations:
        if operation[0] == "prefix":
            results.append(prefix(operation[1]))
        elif operation[0] == "add":
            add(operation[1], operation[2])
        elif operation[0] == "range":
            results.append(prefix(operation[2]) - prefix(operation[1] - 1))
    return results

Trace Lowbit Owners and Inclusive Prefix Subtraction

The actual prefix Lab starts from [3, 1, 4, 2], queries through position 2, adds five at position 1, then queries range [1, 3]. Watch how internal slots 2 and 4 both own the changed position.

print(fenwick_tree_trace([3, 1, 4, 2], [['prefix', 2], ['add', 1, 5], ['range', 1, 3], ['prefix', -1]])) followed by print(fenwick_tree_trace([], []))

Step Executed statement State Why
1 for index, value in enumerate(values): add(index, value) tree = [0, 3, 4, 4, 10] Repeated additions build overlapping owners: slot 2 covers the first two values and slot 4 all four.
2 index += 1; total += tree[index]; index -= index & -index prefix public 2: internal 3 -> 2; total = 4 Slot 3 contributes the single third value.
3 total += tree[index]; index -= index & -index internal 2 -> 0; total = 8 Slot 2 contributes the first two values, completing the prefix without overlap.
4 index += 1; tree[index] += delta; index += index & -index add public 1: internal 2; tree[2] = 9; next owner = 4 The two-value block contains the updated position.
5 tree[index] += delta; index += index & -index tree[4] = 15; next owner = 8 exits; tree = [0, 3, 9, 4, 15] The whole-array block also owns that position and receives the same delta once.
6 results.append(prefix(operation[2]) - prefix(operation[1] - 1)) range [1, 3]: prefix(3) = 15; prefix(0) = 3; result = 12 Only values strictly before left are removed.
7 index += 1; total = 0; return total prefix(-1): internal index = 0; total = 0 The empty prefix reaches internal zero and returns the identity without reading a slot.
8 results.append(prefix(operation[1])); return results results = [8, 12, 0] The caller appends the empty-prefix return after the earlier prefix and range answers.
Print Output
1 [8, 12, 0]
2 []

The prefix query consumes disjoint blocks and the range subtracts only values before the left endpoint. add accepts a delta, so adding five changes the logical value from one to six. prefix(-1) reaches internal zero and returns the neutral sum.

Choose Fenwick or Segment Tree

Choose Fenwick for point updates plus prefix-friendly invertible aggregates such as sums: it is compact and short to implement. Choose a segment tree for arbitrary associative range combines, explicit interval ownership, or extensions such as lazy propagation. If there are no updates, precomputed prefix sums are simpler.

Explain It in an Interview

Say: “Tree slot i stores the aggregate for the block ending at i with length lowbit(i). Queries remove owned blocks; updates climb to every owner.” Trace one prefix in binary, then state O(log n) per operation and O(n) space. See the Python list reference(opens in a new tab) for the underlying array behavior.

Python Version Note

Python 3.11+

The examples use standard Python containers and syntax available in the supported browser runtime; Fenwick Tree itself is taught as an interview abstraction.

Verify in Python docs(opens in a new tab)

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Build by repeated add callsO(n * log(n + 1))O(n * log(n + 1))This actual Lab invokes add for each value; specialized linear construction is not used.
One prefix, range or point additionO(1 + log(n + 1))O(1 + log(n + 1))Valid indices, constant-cost integer arithmetic; prefix(-1) returns zero without reading a tree slot.
Return m operation resultsO(n * log(n + 1) + m * (1 + log(n + 1)))O(n * log(n + 1) + m * (1 + log(n + 1)))Includes the repeated-add build and returned query values; add operations do not produce output.

Space

O(n) for build by repeated add calls; O(1) for one prefix, range or point addition; O(n + m) for return m operation results.

Assumptions

  • This actual Lab invokes add for each value; specialized linear construction is not used.
  • Valid indices, constant-cost integer arithmetic; prefix(-1) returns zero without reading a tree slot.
  • Includes the repeated-add build and returned query values; add operations do not produce output.

Invariants Worth Saying Aloud

  1. Internal slot i owns the block ending at i with length i & -i.
  2. Public zero-based index i becomes internal i+1; slot zero is never an update owner.
  3. Inclusive range [left, right] subtracts prefix(left-1), and prefix(-1) is zero.

When To Use Or Avoid Fenwick Tree

Use It When

  • Use compact Fenwick storage for point deltas and prefix-friendly sums.
  • Translate a replacement into new-minus-old before an additive update if assignment is required.

Choose Another Tool When

  • Use plain prefix sums for immutable input.
  • Use a segment tree for richer associative combines that lack prefix subtraction.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Using a zero-based position as an internal owner

Internal zero has lowbit zero, so an update there cannot advance. The public first value belongs to internal slot one.

Prevent it: Convert public index to index+1 before the update loop.

Avoid

index = public_index
lowbit = index & -index

Use instead

index = public_index + 1
lowbit = index & -index

Subtracting a prefix that already contains the left endpoint

prefix(left) removes the first requested value. Inclusive ranges need only the prefix before left.

Prevent it: Subtract prefix(left-1), with zero for the empty prefix.

Avoid

total = prefix_sums[right] - prefix_sums[left]

Use instead

before_left = prefix_sums[left - 1] if left else 0
total = prefix_sums[right] - before_left

Passing a replacement value as an additive delta

Adding the desired new value to existing state counts the old value again.

Prevent it: When translating assignment, use new_value minus old_value as the delta.

Avoid

delta = new_value
tree[1] += delta
tree[2] += delta

Use instead

delta = new_value - old_value
tree[1] += delta
tree[2] += delta

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.