Sub topic 13
Building a Fenwick Tree in O(n)
This chapter assumes you know the Fenwick tree layout and the lowbit trick i & -i from the previous chapters. It also assumes you are comfortable with 1-indexed arrays and Big-O notation.
The slow way
The obvious build starts with an all-zero tree and calls add(i, x) for each element. Each call costs O(log n), so the whole build costs O(n log n). That is fine for most inputs, but it repeats work that the structure already makes unnecessary.
The key observation
Cell i stores the sum of the range (i - lowbit(i), i]. Its parent is the next cell whose range contains the range of i, which is i + lowbit(i). Every cell's range is therefore the sum of the cell's own element and the ranges of its children.
Suppose you process the cells from left to right. When you reach cell i, all of its children have a smaller index, so they have already pushed their totals into it. Cell i is now complete. You push its total into its parent once and move on. Each cell is pushed exactly once, so the build is O(n).
The code
class Fenwick:
# 1-indexed Fenwick tree for prefix sums.
def __init__(self, n):
self.n = n
self.t = [0] * (n + 1)
def add(self, i, delta):
while i <= self.n:
self.t[i] += delta
i += i & -i
def prefix(self, i):
s = 0
while i > 0:
s += self.t[i]
i -= i & -i
return s
def fenwick_from_list(a):
# Builds a Fenwick tree in O(n) by pushing each cell into its parent once.
f = Fenwick(len(a))
for i, x in enumerate(a, start=1):
f.t[i] += x
j = i + (i & -i)
if j <= f.n:
f.t[j] += f.t[i]
return f
f = fenwick_from_list([5, 2, 7, 1, 3])
print(f.t[1:]) # [5, 7, 7, 15, 3]
print(f.prefix(5)) # 18Tracing it
For [5, 2, 7, 1, 3]:
i = 1:t[1] = 5. Push 5 into cell 2.i = 2:t[2] = 5 + 2 = 7. Push 7 into cell 4.i = 3:t[3] = 7. Push 7 into cell 4.i = 4:t[4] = 14 + 1 = 15. The parent index is 8, which is out of range, so nothing is pushed.i = 5:t[5] = 3. The parent index is 6, which is out of range.
The result [5, 7, 7, 15, 3] is the same tree you would get from five calls to add. As a check, prefix(5) = t[5] + t[4] = 3 + 15 = 18.
Common errors
- Using
=instead of+=forf.t[i] += x. The cell already holds contributions from its children, so assigning overwrites them. - Skipping the
j <= f.ncheck. This raises anIndexError, or silently writes outside the tree in languages without bounds checks. - Enumerating from 0. The structure is 1-indexed, so use
start=1.
Exercise
A Fenwick tree has n = 7. For each index 1 to 7, give the parent index i + (i & -i) that the O(n) build pushes into, or say that the cell has no parent in range.
Show answer
1 → 2, 2 → 4, 3 → 4, 4 → 8 (none), 5 → 6, 6 → 8 (none), 7 → 8 (none). Cells 4, 6 and 7 push nothing because their parent index exceeds 7.