Skip to content

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.

16 min read0/4 questions

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.

StructureBuildPoint updateRange queryGood for
Plain arrayO(1)O(1)O(n)few queries
Prefix sum arrayO(n)O(n)O(1)no updates
Fenwick treeO(n)O(log n)O(log n)sums, counts
Segment treeO(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 the lowbit(i) elements ending at position i.
  • So tree[6] (binary 110, 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.

Fenwick tree over [5, 2, 9, 1, 4, 7, 3, 6]
0
5
1
7
2
9
3
17
4
4
5
11
6
3
7
37
8

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.

1/7

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.

Python
import random class Fenwick: """Point update, prefix sum. Both O(log n). Index 1..n inside.""" def __init__(self, n): self.n = n self.tree = [0] * (n + 1) # tree[0] is unused def add(self, i, delta): # i is 0-based for callers i += 1 while i <= self.n: self.tree[i] += delta i += i & -i # climb to the next node that covers i def prefix(self, i): # sum of the first i elements total = 0 while i > 0: total += self.tree[i] i -= i & -i # drop the lowest set bit return total def range_sum(self, l, r): # inclusive, 0-based return self.prefix(r + 1) - self.prefix(l) class NumArray: """Range Sum Query - Mutable.""" def __init__(self, nums): self.nums = list(nums) self.fw = Fenwick(len(nums)) for i, x in enumerate(nums): self.fw.add(i, x) def update(self, i, val): # the problem SETS a value; Fenwick ADDS self.fw.add(i, val - self.nums[i]) self.nums[i] = val def sum_range(self, l, r): return self.fw.range_sum(l, r) na = NumArray([1, 3, 5])assert na.sum_range(0, 2) == 9na.update(1, 2)assert na.sum_range(0, 2) == 8 and na.sum_range(1, 1) == 2 random.seed(11)for _ in range(100): arr = [random.randint(-9, 9) for _ in range(random.randint(1, 20))] na = NumArray(arr) for _ in range(50): if random.random() < 0.5: i = random.randrange(len(arr)); v = random.randint(-9, 9) arr[i] = v; na.update(i, v) else: l = random.randrange(len(arr)); r = random.randrange(l, len(arr)) assert na.sum_range(l, r) == sum(arr[l:r + 1])print("Fenwick matches brute force")fw = Fenwick(8)for i, x in enumerate([5, 2, 9, 1, 4, 7, 3, 6]): fw.add(i, x)print(fw.tree)print([i & -i for i in range(1, 9)])
Output
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.

Predict the outputPython

What does this print?

i, path = 13, []
while i > 0:
  path.append(i)
  i -= i & -i
print(path)
Need a nudge? Hints walk you through it.
Put it in order4 steps

In a Fenwick tree of size 16, put the slots that add(5, delta) touches in the order it touches them.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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.

Segment tree query: sum of positions 2 to 6
00-110-322-330-744-554-766-77

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.

1/5

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.

Python
import random class SegmentTree: """Range query + point update for any associative combine (sum, min, max).""" def __init__(self, nums, combine=lambda a, b: a + b, identity=0): self.n = len(nums) self.combine, self.identity = combine, identity self.tree = [identity] * (4 * self.n) # 4n is always enough room self._build(nums, 1, 0, self.n - 1) def _build(self, nums, node, lo, hi): if lo == hi: self.tree[node] = nums[lo] return mid = (lo + hi) // 2 self._build(nums, 2 * node, lo, mid) self._build(nums, 2 * node + 1, mid + 1, hi) self.tree[node] = self.combine(self.tree[2 * node], self.tree[2 * node + 1]) def update(self, i, val, node=1, lo=0, hi=None): hi = self.n - 1 if hi is None else hi if lo == hi: self.tree[node] = val return mid = (lo + hi) // 2 if i <= mid: self.update(i, val, 2 * node, lo, mid) else: self.update(i, val, 2 * node + 1, mid + 1, hi) self.tree[node] = self.combine(self.tree[2 * node], self.tree[2 * node + 1]) def query(self, l, r, node=1, lo=0, hi=None): hi = self.n - 1 if hi is None else hi if r < lo or hi < l: # no overlap return self.identity if l <= lo and hi <= r: # node fully inside the query return self.tree[node] mid = (lo + hi) // 2 # partial overlap: ask both children return self.combine(self.query(l, r, 2 * node, lo, mid), self.query(l, r, 2 * node + 1, mid + 1, hi)) a = [5, 2, 9, 1, 4, 7, 3, 6]sums = SegmentTree(a)mins = SegmentTree(a, combine=min, identity=float("inf"))assert sums.query(2, 6) == 24assert mins.query(2, 6) == 1sums.update(3, 10); mins.update(3, 10)assert sums.query(2, 6) == 33 and mins.query(2, 6) == 3 random.seed(12)for _ in range(100): arr = [random.randint(-50, 50) for _ in range(random.randint(1, 25))] st = SegmentTree(arr, combine=max, identity=float("-inf")) for _ in range(40): if random.random() < 0.4: i = random.randrange(len(arr)); arr[i] = random.randint(-50, 50); st.update(i, arr[i]) else: l = random.randrange(len(arr)); r = random.randrange(l, len(arr)) assert st.query(l, r) == max(arr[l:r + 1])print("segment tree matches brute force for sum, min and max")print(sums.query(0, 7), mins.query(0, 7))
Output
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.

Python
import random class MinSegTree: """Iterative bottom-up segment tree: leaves at tree[n:], parents above.""" def __init__(self, nums): self.n = len(nums) self.tree = [0] * self.n + list(nums) for i in range(self.n - 1, 0, -1): self.tree[i] = min(self.tree[2 * i], self.tree[2 * i + 1]) def update(self, i, val): i += self.n self.tree[i] = val while i > 1: i //= 2 self.tree[i] = min(self.tree[2 * i], self.tree[2 * i + 1]) def query(self, l, r): # inclusive l, inclusive r best = float("inf") l += self.n; r += self.n + 1 # half-open [l, r) over the leaves while l < r: if l & 1: # l is a right child: take it, step right best = min(best, self.tree[l]); l += 1 if r & 1: # r is a right child: take its left sibling r -= 1; best = min(best, self.tree[r]) l //= 2; r //= 2 return best random.seed(13)for _ in range(200): arr = [random.randint(0, 99) for _ in range(random.randint(1, 30))] st = MinSegTree(arr) for _ in range(40): if random.random() < 0.4: i = random.randrange(len(arr)); arr[i] = random.randint(0, 99); st.update(i, arr[i]) else: l = random.randrange(len(arr)); r = random.randrange(l, len(arr)) assert st.query(l, r) == min(arr[l:r + 1])print("iterative min tree matches brute force, including odd lengths")
Output
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.)

Quick check
You need range MINIMUM queries on an array that also gets point updates. Which structure fits?
Need a nudge? A hint rules out a wrong answer.

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.

Python
import randomfrom bisect import bisect_left, insort def count_smaller(nums): """Count of Smaller Numbers After Self, O(n log n).""" ranks = {v: i + 1 for i, v in enumerate(sorted(set(nums)))} # compress to 1..m m = len(ranks) tree = [0] * (m + 1) # Fenwick over ranks: how many seen def add(i): while i <= m: tree[i] += 1 i += i & -i def prefix(i): total = 0 while i > 0: total += tree[i] i -= i & -i return total out = [] for x in reversed(nums): # everything already added is to the RIGHT of x r = ranks[x] out.append(prefix(r - 1)) # strictly smaller ranks add(r) return out[::-1] def count_smaller_insort(nums): """Simpler: keep the right side sorted. insort is O(n) per insert.""" seen, out = [], [] for x in reversed(nums): out.append(bisect_left(seen, x)) # how many seen values are < x insort(seen, x) return out[::-1] def brute(nums): return [sum(1 for y in nums[i + 1:] if y < x) for i, x in enumerate(nums)] assert count_smaller([5, 2, 6, 1]) == [2, 1, 1, 0]assert count_smaller([-1, -1]) == [0, 0]assert count_smaller([]) == []assert count_smaller([10**9, -10**9, 0]) == [2, 0, 0] # huge values: compression handles them random.seed(14)for _ in range(300): nums = [random.randint(-20, 20) for _ in range(random.randint(0, 30))] assert count_smaller(nums) == count_smaller_insort(nums) == brute(nums)print(count_smaller([5, 2, 6, 1]))
Output
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.insort finds 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 why count_smaller_insort above is a reasonable first answer. On large adversarial inputs it degrades to O(n²).
  • sortedcontainers.SortedList is a third-party package, not in the standard library, giving roughly O(log n) add, remove, bisect_left and 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 / TreeSet and std::set / std::multiset, which is why so many editorial solutions use them.
with_sortedlist.py
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 heapq is a min-heap; negate values for a max-heap, or on Python 3.14+ use heapq.heappush_max and heappop_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 the pairs0/5 matched

Match each task to the simplest structure that handles it well.

Choose an item, then its match on the other side.
Key terms
Fenwick tree
A 1-indexed array where slot i sums the i & -i elements 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.