Practice Discrete Math

Algorithms / Fenwick Tree Prefix Sum

Least You Need to Know: Fenwick Trees, Prefix Sums, and Low-Bit Jumps

Fenwick trees support prefix-sum queries and point updates in `O(log n)` by storing carefully chosen partial sums. The key bit trick is the low bit, which tells how large a range each index is responsible for.

جو کم از کم جاننا ضروری ہے

اہم علامتیں

lowbit(x) = x & -x size of the segment represented at index x
prefix(r) sum of positions 1 through r
range(l, r) prefix(r) - prefix(l - 1)

مختصر حل شدہ مثال

  • Suppose you need many updates and prefix sums over an array.
  • In a Fenwick tree, index `i` stores a sum covering the last `lowbit(i)` positions ending at `i`.
  • To query `prefix(r)`, keep adding tree values and move `r` downward by `lowbit(r)`.
  • The path length is logarithmic because each step removes the lowest set bit.

عام غلطیاں

اس قسم کے سوال کو کیسے پہچانیں

Next recommended lesson

Continue through this topic with Least You Need to Know: Cycle Detection in Directed and Undirected Graphs.

Least You Need to Know: Cycle Detection in Directed and Undirected Graphs

Related lessons

Keep going with nearby lessons in the same topic.

More ways to explore

مشق شروع کریں