Skip to main content

Segment Tree vs Fenwick Tree

Short answer

A Fenwick tree if you only need prefix sums with point updates, because it is a fraction of the code and uses less memory. A segment tree for anything else: minimums, maximums, range updates, or any operation that does not decompose into prefixes.

Both give O(log n) updates and queries over an array, and for prefix sums they do the same job. The Fenwick tree is dramatically smaller: one array, two loops of three lines each, and no recursion. The segment tree is more code and more memory, and it can do things the Fenwick tree fundamentally cannot.

Side by side

DimensionSegment TreeFenwick Tree
Query and updateO(log n)O(log n)
Memory4n, for a safe tree layoutn plus 1
Code sizeSubstantially moreAbout ten lines
Sum queriesYesYes
Min or max queriesYesNo, they do not decompose into prefixes
Range updatesYes, with lazy propagationOnly via a difference-array trick
Constant factorHigherLower, the loops are tiny

When to pick each

Segment Tree

  • The operation is a minimum, a maximum, or a greatest common divisor, where a prefix decomposition does not exist.
  • You need range updates as well as range queries, which lazy propagation handles.
  • Each node needs to store something richer than a number, such as a sorted list in a merge sort tree.
See it step by step

Fenwick Tree

  • Prefix sums with point updates, which is the case it was designed for.
  • Memory is tight, since it needs one array rather than four times the input.
  • You are writing under time pressure and want the shortest correct thing.
See it step by step
The mistake to avoid

Trying to use a Fenwick tree for range minimum queries. It looks like it should work, and it does not: subtracting a prefix from a prefix is meaningful for sums and meaningless for minimums, because you cannot remove an element's contribution from a minimum once other values are involved. Range minimum with updates needs a segment tree; range minimum without updates can use a sparse table for O(1) queries.

Questions people ask

Why is the Fenwick tree array n plus 1?

It is one-indexed, because the whole structure relies on isolating the lowest set bit, and index zero has none. Slot zero is left unused rather than special-cased.

Can a Fenwick tree do range updates?

For point queries, yes, by storing differences and updating two positions. For range updates with range queries you need two Fenwick trees and some care, at which point a lazy segment tree is usually the clearer choice.

What about a sparse table?

It answers minimum queries in O(1) rather than O(log n), but it cannot handle updates at all, since one changed element invalidates every block containing it. Use it for static data, and a segment tree when the array changes.

Read next

Other comparisons