progress

~/problems / Range queries / Fenwick tree (BIT)

Which cells a Fenwick tree touches

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

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) -> int for i >= 1.
  • update_indexes(i, n) -> list[int]: the cells add(i, delta) changes, in order: start at i and keep adding lowbit while <= n.
  • query_indexes(i) -> list[int]: the cells prefix_sum(i) reads, in order: start at i and keep subtracting lowbit while > 0. Their ranges cover 1..i exactly 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
Fenwick cells 1 to 16, each drawn as a bar over the positions it sums, ending at its own index with length lowbit(j). Adding at 5 touches cells 5, 6, 8 and 16; the prefix sum up to 13 reads cells 13, 12 and 8, which cover 13, 9 to 12 and 1 to 8.
Show hint

updates climb with i += i & -i, queries descend with i -= i & -i; both take O(log n) steps.

Topic: Fenwick tree (BIT). Point update + prefix sum in O(log n) with i & -i.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc