Data Structures19 sections · 729 units
Open in Course

Intro

Why Fenwick Trees matter

Segment trees are powerful but verbose. For many problems, you only need prefix queries (sum of elements 00 to ii), not arbitrary range queries.

Fenwick Trees (also called Binary Indexed Trees or BITs) provide:

  • O(logn)O(\log n) prefix sum queries
  • O(logn)O(\log n) point updates
  • Only nn extra space (not 4n4n like segment trees)
  • About 10 lines of code The tradeoff: Fenwick Trees directly support only prefix queries.

For range [l,r][l, r], compute prefix(r)prefix(l1)\text{prefix}(r) - \text{prefix}(l-1). For range minimum queries, Fenwick Trees don't work directly. In this section, I'll teach you how Fenwick Trees use bit manipulation to achieve logarithmic operations, and when to choose them over segment trees.