Data Structures19 sections · 729 units
Open in Course

Lowest Set Bit

The lowbit operation

The lowest set bit of ii you can compute as:

def lowbit(i):
    return i & (-i)
``` Why does this work? In two's complement, $-i$ is computed by flipping all bits of $i$ and adding $1$. 

This causes all bits below the lowest $1$ to flip back to $0$, and the lowest $1$ remains. The AND isolates just that bit. 

Example: $i = 12$ (binary $1100$) - $-i = -12$ (binary $...11110100$ in two's complement, last $4$ bits are $0100$) - $i \land (-i) = 0100 = 4$ This operation is the heart of Fenwick Trees. 

Every query and update uses it. Time: $O(\log n)$. Space: $O(n)$.