Builds onPrefix sumsTree basics
01The idea
Prefix sums answer any range sum in O(1), but only while the array never changes. One update means rebuilding the prefix array, which costs O(n). When a problem mixes many updates with many range queries, you need a structure that does both in O(log n).
A Fenwick tree, also called a binary indexed tree, keeps sums in overlapping blocks. With positions numbered from 1, tree[i] holds the sum of a block that ends at i. The block's length is the lowest 1 bit of i, which is i & -i. So tree[6] covers positions 5 to 6, tree[4] covers 1 to 4, and tree[5] covers only 5.
Two operations use those blocks:
- To get the sum of positions 1 to i, add
tree[i]and move toi - (i & -i), the end of the block before it. Repeat until i is 0. - To add to position i, add to
tree[i]and move toi + (i & -i), the next block that also covers i. Repeat while i is in range.
Each step removes or adds one bit, so both take O(log n). A range sum from l to r is the sum up to r minus the sum up to l - 1.
A segment tree does the same job in a different shape. It is a binary tree where each node stores the answer for a range of the array. It is longer to write, but it also handles minimum, maximum, or updates to whole ranges, which are harder to do with a Fenwick tree.
02How to spot it
Use a Fenwick tree or a segment tree when:
- the problem has many updates and many range queries mixed together, such as "update index i" and "sum from l to r"
- both counts are large, around 10⁵ each, so O(n) per query is too slow
- you count, for each item, how many earlier items are smaller or bigger. Index the tree by value and add each item as you pass it
If the array never changes, plain prefix sums are simpler. If the query is a minimum or maximum over a range with updates, reach for a segment tree. If values are huge but few, first map them to ranks 1 to n.
Sign in to read the rest of this lesson
The worked example, the interactive visualization, the code template and a short quiz that marks the lesson as done in your study plans.
Sign in to continue