Data Structures19 sections · 729 units
Open in Course

BIT for XOR Queries

Another invertible operation

BIT works for any invertible operation. XOR is self-inverse: aa=0a \oplus a = 0.

def queryXOR(i):
    result = 0
    while i > 0:
        result ^= tree[i]
        i -= i & (-i)
    return result

def updateXOR(i, val):
    while i <= n:
        tree[i] ^= val
        i += i & (-i)

Range XOR from ll to rr: prefix(r)prefix(l1)\text{prefix}(r) \oplus \text{prefix}(l-1).

Use case: problems involving XOR of subarrays, toggling bits in ranges, or maintaining XOR over dynamic data.