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−lo)/2 not (lo+hi)/2 to avoid overflow with 32-bit integers.