Sub topic 10
The lowbit trick: isolating the lowest set bit
This chapter assumes you know binary numbers, bitwise AND, and two's complement negation. The Fenwick tree in the next chapters depends on one small expression, i & -i. Here you learn what it computes and why it moves you around the tree.
What lowbit computes
The lowest set bit of i is the rightmost 1 in its binary form. i & -i returns a number with only that bit set. We call this value lowbit.
Two's complement negation means -i is ~i + 1. Flipping all bits turns trailing zeros into ones and the lowest 1 into a 0. Adding 1 carries through those trailing ones, which restores the lowest 1 and the zeros below it. Every bit above that position stays flipped. ANDing with the original keeps only the lowest set bit.
Take i = 12:
12is01100-12is1010012 & -12is00100, which is 4
| i | Binary | lowbit(i) |
|---|---|---|
| 1 | 0001 | 1 |
| 2 | 0010 | 2 |
| 3 | 0011 | 1 |
| 4 | 0100 | 4 |
| 5 | 0101 | 1 |
| 6 | 0110 | 2 |
| 7 | 0111 | 1 |
| 8 | 1000 | 8 |
Why it matters for Fenwick trees
In a Fenwick tree, cell i stores the sum of the lowbit(i) elements ending at i. It covers positions i - lowbit(i) + 1 through i. Cell 6 covers 5 to 6. Cell 4 covers 1 to 4. Cell 8 covers 1 to 8.
Two moves follow from this:
i += lowbit(i)goes to the next cell whose range containsi. Point updates use this move.i -= lowbit(i)removes the lowest set bit and jumps to the end of the block just before this one. Prefix queries use this move.
Each move changes the bit pattern so that the number of steps is at most the number of bits in i, which is O(log n).
Walking the paths
def lowbit(i):
return i & -i
def update_path(i, n):
path = []
while i <= n:
path.append(i)
i += lowbit(i)
return path
def query_path(i):
path = []
while i > 0:
path.append(i)
i -= lowbit(i)
return path
print(update_path(3, 8)) # [3, 4, 8]
print(update_path(5, 8)) # [5, 6, 8]
print(query_path(7)) # [7, 6, 4]The query path for 7 reads three cells. Cell 7 covers position 7, cell 6 covers 5 to 6, and cell 4 covers 1 to 4. These blocks do not overlap, and together they make up the prefix 1 to 7.
Exercise
What is the update path for index 6 in a Fenwick tree of size 10, and which blocks does the query path for 10 read?
Show answer
Update path: 6 (lowbit 2) goes to 8 (lowbit 8), which goes to 16 and stops, so the cells are [6, 8]. Query path for 10: 10 (binary 1010, lowbit 2) goes to 8 (lowbit 8), which goes to 0, so it reads cells 10 and 8. Cell 10 covers positions 9 to 10 and cell 8 covers 1 to 8.