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)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 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.
def fenwick_block_ranges(n):
return [[index - (index & -index) + 1, index] for index in range(1, n + 1)]Implement fenwick_block_ranges(n). Return [left, right] one-based inclusive ranges owned by Fenwick slots 1 through n. n is a nonnegative integer.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
def fenwick_block_ranges(n):
return [[index - (index & -index) + 1, index] for index in range(1, n + 1)]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.
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.
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 resultsImplement 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.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
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 resultsThe 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. |
| 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 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.
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 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)Interview bounds depend on the stated representation, input model, and real Python operations.
| Operation | Average | Worst | Interview note |
|---|---|---|---|
| Build by repeated add calls | O(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 addition | O(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 results | O(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. |
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.
These are the mistakes most likely to survive a happy-path example and fail a boundary case.
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.
index = public_index
lowbit = index & -indexindex = public_index + 1
lowbit = index & -indexWhere you will hit this: Prefix and Range Sums with a Fenwick Tree(opens in a new tab)
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.
total = prefix_sums[right] - prefix_sums[left]before_left = prefix_sums[left - 1] if left else 0
total = prefix_sums[right] - before_leftWhere you will hit this: Prefix and Range Sums with a Fenwick Tree(opens in a new tab)
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.
delta = new_value
tree[1] += delta
tree[2] += deltadelta = new_value - old_value
tree[1] += delta
tree[2] += deltaWhere you will hit this: Map Sum Pairs(opens in a new tab)
Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.
python-docs · checked 2026-07-27