Lesson 38 of 40Strings, math and design
Fenwick Trees, Segment Trees and Sorted Containers
Answer range queries while the data keeps changing: Fenwick trees, segment trees, coordinate compression and sorted lists, with honest advice on when you need them.
A trading dashboard shows the total volume between any two minutes of the day, and new trades keep changing those minutes while people query. A game leaderboard answers "how many players scored less than you?" millions of times while scores change every second. A prefix sum array answers a range query in O(1), but one update makes every prefix after it stale. These structures fix that: both the update and the query cost O(log n). A fair warning first: they are rare in standard interviews and common in online assessments, especially the hard tier of timed coding tests, and in Google and trading-firm loops. Learn the Fenwick tree well enough to write it from memory, and the segment tree well enough to explain it and adapt a template.
The problem: updates and queries interleaved
You have an array of n numbers and a stream of q operations, each either "set a[i] to v" or "what is the sum (or min, or max) of a[l..r]?" Here is what each structure costs.
| Structure | Build | Point update | Range query | Good for |
|---|---|---|---|---|
| Plain array | O(1) | O(1) | O(n) | few queries |
| Prefix sum array | O(n) | O(n) | O(1) | no updates |
| Fenwick tree | O(n) | O(log n) | O(log n) | sums, counts |
| Segment tree | O(n) | O(log n) | O(log n) | sum, min, max, gcd, anything associative |
With n and q both around 10^5, the first two rows each cost about 10^10 steps in the worst case. The last two cost about 10^5 × 17, which runs in well under a second even in Python. That gap is the whole reason these structures exist. You saw the prefix array and its limits in Prefix Sums and Difference Arrays; this lesson picks up from the "updates mixed with queries" case there.
Fenwick tree: prefix sums that can change
A Fenwick tree (also called a binary indexed tree, or BIT) is an array, 1-indexed, where each slot stores the sum of a block of the original array. The size of the block is decided by the lowest set bit of the index, which you get with i & -i (the "lowbit"). As you saw in Bit Manipulation, two's complement makes -i flip every bit above the lowest 1, so AND keeps only that bit.
tree[i]stores the sum of thelowbit(i)elements ending at positioni.- So
tree[6](binary110, lowbit 2) covers positions 5 and 6.tree[8](lowbit 8) covers 1 to 8.tree[7](lowbit 1) covers only 7.
Prefix query prefix(i): add tree[i], then jump to i - lowbit(i), the position just before that block, and repeat until 0. Each jump clears one set bit, so there are at most log n jumps.
Update add(i, delta): add delta to tree[i], then jump to i + lowbit(i), the next block that also covers position i, until you pass n. Each jump moves the lowest set bit up, so again at most log n jumps.
Slot 0 is unused. tree[i] covers the i & -i elements ending at position i: tree[4] = 5+2+9+1 = 17, tree[6] = 4+7 = 11, tree[8] = all eight = 37.
The whole structure is about fifteen lines. The 1-indexing is not optional: lowbit of 0 is 0, so a 0-based loop would never move. Keep the tree 1-based inside and convert at the edges.
Range Sum Query - Mutable asks for update(i, val) that sets a value, while a Fenwick tree adds. Keep a copy of the array and add the difference val - nums[i]. Forgetting this and adding val itself is the most common bug.
Press Run (⌘ Enter) to see what happens.Building with n calls to add is O(n log n), which is fine. There is an O(n) build (add each tree[i] into tree[i + lowbit(i)] once), worth mentioning if asked. Range sums come from two prefix queries, exactly like a prefix array. What a Fenwick tree cannot do directly is range min or max, because you cannot "subtract" a minimum. That is the segment tree's job.
What does this print?
i, path = 13, [] while i > 0: path.append(i) i -= i & -i print(path)
In a Fenwick tree of size 16, put the slots that add(5, delta) touches in the order it touches them.
- Tap the steps below in the right order.
Segment tree: any associative query
A segment tree is a binary tree where each node stores the answer for a range: the root covers the whole array, its children cover the two halves, and so on down to single elements at the leaves. Any operation that is associative (combining left then right gives the same result however you group it) works: sum, min, max, gcd, bitwise OR, even "max subarray sum" with a richer node.
To answer a query on [l, r], start at the root and split into three cases at every node:
- No overlap with
[l, r]: return the identity (0 for sum, infinity for min). - Fully inside
[l, r]: return the stored value without going further. - Partial overlap: ask both children and combine.
At most four nodes per level are ever visited, so a query touches O(log n) nodes. An update changes one leaf and recomputes the O(log n) ancestors above it.
Each node is labelled with the positions it covers, over the array [5, 2, 9, 1, 4, 7, 3, 6]. The root stores 37, the sum of everything.
The recursive version below stores the tree in an array where node k has children 2k and 2k + 1, the same layout as a heap. Allocate 4n slots: when n is not a power of two the tree is not perfect, and 4n is a safe upper bound. Passing combine and identity lets one class serve sum, min and max.
Press Run (⌘ Enter) to see what happens.The iterative bottom-up version (shorter, faster in Python)
Competitive programmers often use a non-recursive layout: leaves live at tree[n:], and each parent i is the combination of 2i and 2i + 1. A query walks two pointers up from the leaves. When the left pointer is a right child, its node is fully inside the range, so take it and step right. When the right pointer (half-open) is a right child, take its left sibling. Then both climb one level. No recursion, no 4n allocation, and it works for any n, not only powers of two.
Press Run (⌘ Enter) to see what happens.Because it collects pieces from both ends at once, this version combines them out of order. That is fine for commutative operations like sum, min and max. For a non-commutative combine (such as matrix products or "max subarray" nodes) keep separate left and right accumulators, or use the recursive version.
Range updates and lazy propagation. If the problem also asks "add 5 to every element in [l, r]", updating every leaf is O(n). Lazy propagation stores a pending update on a node that is fully covered and only pushes it down to the children when a later query or update needs to look inside. Both operations stay O(log n). It is a solid half page of careful code, and interviews almost never ask you to write it; know that it exists and what problem it solves. (If you only need range add with point queries, a Fenwick tree over a difference array does it without lazy propagation.)
Counting with a Fenwick tree: Count of Smaller Numbers After Self
"For each element, count how many elements to its right are smaller." The brute force is O(n²). The trick is to walk right to left and keep a Fenwick tree of counts by value: before inserting x, prefix(rank(x) - 1) tells you how many already-seen values (all to the right of x) are smaller.
Values can be as large as 10^9 or negative, and a Fenwick tree needs small positive indices. Coordinate compression fixes that: sort the distinct values and replace each with its rank, 1 to m. Only the relative order matters for "smaller than", so nothing is lost. Compression is a general tool; it shows up whenever values are huge but there are few of them.
The other classic solution is merge sort: while merging, every time you take an element from the left half, the number of right-half elements already taken is how many smaller elements came after it. Both are O(n log n). The Fenwick version is easier to get right under pressure.
Press Run (⌘ Enter) to see what happens.The same skeleton (compress, sweep, Fenwick of counts) solves Count of Range Sum, Reverse Pairs and "count inversions", which is why it is worth knowing.
Sorted containers: the practical shortcut
Many range-query problems are really "keep a collection sorted while inserting and deleting, and ask for rank or neighbours". In Python and JavaScript, the honest picture is this.
bisect.insortfinds the position in O(log n) but inserting into a list shifts everything after it: O(n) per insert. Because the shift is one fast memory move in C, it is often fine up to around 10^5 elements, which is whycount_smaller_insortabove is a reasonable first answer. On large adversarial inputs it degrades to O(n²).sortedcontainers.SortedListis a third-party package, not in the standard library, giving roughly O(log n)add,remove,bisect_leftand indexing. LeetCode's Python environment includes it; many online assessment platforms and the in-browser Python here do not. Ask, or check the platform's documentation.- JavaScript has no balanced BST or sorted list built in. For a JS solution you write a Fenwick tree, a segment tree, or a heap-based workaround. This is one practical reason to know the Fenwick tree cold if JavaScript is your interview language.
- Java and C++ have
TreeMap/TreeSetandstd::set/std::multiset, which is why so many editorial solutions use them.
from sortedcontainers import SortedList # third-party: pip install sortedcontainers
def count_smaller(nums):
seen, out = SortedList(), []
for x in reversed(nums):
out.append(seen.bisect_left(x)) # O(log n)
seen.add(x) # O(log n) amortised, no O(n) shift
return out[::-1]When you need these, and when you do not
Most interview problems that look like range queries have a simpler answer. Before reaching for a tree, check:
- No updates? A prefix sum array. For static range min, a sparse table gives O(1) queries, but even that is rare.
- Only need the global max or min while values change? A heap with lazy deletion, as in Max Stack in Design Problems: LRU Cache, Iterators and Friends. Python's
heapqis a min-heap; negate values for a max-heap, or on Python 3.14+ useheapq.heappush_maxandheappop_max. Say which version you assume, because many platforms still run older Python. - Sliding window min or max? A monotonic deque, O(n) total.
- Offline queries (all known in advance)? Sorting the queries and sweeping often removes the need for updates entirely.
Reach for Fenwick or segment trees when updates and queries genuinely interleave, or when you need order statistics ("how many smaller") over a changing set. Signals in the problem statement: n and q both up to 10^5 or more, the words "update" and "query" in the same API, or "count pairs i < j with a[i] > a[j]".
Match each task to the simplest structure that handles it well.
- Fenwick tree
- A 1-indexed array where slot i sums the
i & -ielements ending at i. Prefix sums and point updates in O(log n). - lowbit
i & -i, the value of the lowest set bit of i. It decides block sizes and jumps in a Fenwick tree.- segment tree
- A binary tree of ranges where each node stores the answer for its range. Any associative query plus updates in O(log n).
- lazy propagation
- Storing a pending range update on a segment tree node and pushing it to the children only when needed, keeping range updates O(log n).
- coordinate compression
- Replacing values with their rank among the distinct values, so huge or negative numbers become small array indices.
- associative
- An operation where (a op b) op c equals a op (b op c), such as sum, min, max and gcd. Required for a segment tree.
- SortedList
- A third-party Python sorted container with about O(log n) insert, remove and rank. Not in the standard library.