A Fenwick tree is a 1-indexed array t[1..n] where cell j holds the sum of positions j - lowbit(j) + 1 .. j, with lowbit(j) = j & -j (the lowest set bit). Its operations are just walks over indexes. Write the walks, returning indexes instead of summing:
lowbit(i) -> intfori >= 1.update_indexes(i, n) -> list[int]: the cellsadd(i, delta)changes, in order: start atiand keep addinglowbitwhile<= n.query_indexes(i) -> list[int]: the cellsprefix_sum(i)reads, in order: start atiand keep subtractinglowbitwhile> 0. Their ranges cover1..iexactly once;query_indexes(0)is[].
lowbit(12) # 4 (12 = 0b1100)
update_indexes(5, 16) # [5, 6, 8, 16]
query_indexes(13) # [13, 12, 8] ranges 13..13, 9..12, 1..8
Show hint
updates climb with i += i & -i, queries descend with i -= i & -i; both take O(log n) steps.