Bug 1: Off-by-one in rank rank(B,i) counts bits in [0,i) not [0,i].
Use rank(B,r+1)−rank(B,l) for range [l,r]. Bug 2: Wrong child selection For value v with mid=(lo+hi)/2: - v≤mid: go left - v>mid: go right Bug 3: Forgetting coordinate compression If values exceed 106, wavelet tree depth becomes problematic.
Always compress. Bug 4: Integer overflow in mid Use (lo+hi)/2 not lo+(hi−lo)/2 if values are non-negative. Watch for overflow with 32-bit integers.