Segment Tree & Fenwick Tree

Answer range queries and change elements in O(log n) each: the segment tree for any combinable operation, lazy propagation for range updates, and the smaller Fenwick tree for prefix sums.

Overview

The problem it solves

You have an array and two kinds of requests arrive in any order: change one element, and ask for the sum (or the minimum, or the maximum) of a range. A plain array makes changes free and queries slow. A prefix-sum array makes queries free and changes slow, because every prefix after the change must be rebuilt. A segment tree makes both cost O(log n).

Put in numbers, a plain array changes one element in O(1) but sums a range in O(n), and it needs no extra space. Prefix sums turn that around: a range sum is O(1), a change is O(n), and the prefix array takes O(n) extra space. A segment tree and a Fenwick tree both sit in the middle, with O(log n) for a change, O(log n) for a range sum and O(n) extra space. This chapter builds the segment tree first and comes back to the Fenwick tree near the end.

The trick is to store answers for ranges of many sizes ahead of time, so any query range can be assembled from a few stored pieces, and any change touches only the pieces that contain it.

Sign up free to read the full topic

More Coding & DSA topics

Start free on Cariara · Coding problems · System design studio