Fenwick Trees
In short: a Fenwick tree keeps one flat list where cell i owns a range
of i & -i minutes ending at i, found with the lowest-set-bit trick. A
prefix query jumps down, clearing the lowest set bit each step; a point
update jumps up, adding it — both in O(log n) hops. It needs an aggregate
with an inverse (sum, count, XOR), because a range answer is still prefix
minus prefix; min has no inverse, which is what the segment tree is for.
![A Fenwick list of 8 cells; T[4] is labelled "owns 1-4", and prefix(7) reads T[7], T[6] and T[4]](/api/assets/dsa/assets/76170b01e1decade.png)
Square-root blocks got Quarry to O(√n) for both edits and queries. On a month-long log that is a couple of hundred reads, which is fine for one dashboard and not fine for the live counter on Quarry's status page. There, every incoming request is an edit and every refresh is a query, thousands of each per second.
The block idea had one level of summaries. What if there were summaries of summaries, and summaries of those, each level twice as coarse as the one below? Then any prefix could be assembled from about log₂ n pieces. A Fenwick tree (also called a binary indexed tree) does exactly that, and it does it in a single flat list the same length as the log, with no pointers and no nodes. It needs one bit trick. Everything else follows from it.
The lowest set bit
For a positive integer i, i & -i keeps only its lowest 1 bit. Python's
integers are two's-complement for bitwise operations, so -i is "flip every bit
and add one", which leaves the lowest set bit as the only bit the two share.
print(12 & -12, 10 & -10, 7 & -7)