Segment tree
hard 24 minA segment tree is a binary tree in which every node stores the answer (sum, min, max, GCD) for one range of an array.
See it run
Every node stores the answer for one range, so a query or an update only walks a few root-to-leaf paths.
Operations
Build
Build a sum segment tree over [1, 3, 5, 7, 9, 11, 13, 15]: split each range in half, fill the leaves, and set every parent to the sum of its two children on the way back up.
Step 1 of 9
The input
- 10
- 31
- 52
- 73
- 94
- 115
- 136
- 157
Eight values, indexes 0 to 7. We want fast answers to sum of a[l..r] while values keep changing. First we allocate tree with 4n = 32 slots; the root lives at slot 1.
Step 1: The input
def build(a, tree, node, lo, hi): if lo == hi: # leaf: one element tree[node] = a[lo] return mid = (lo + hi) // 2 build(a, tree, 2 * node, lo, mid) # left half build(a, tree, 2 * node + 1, mid + 1, hi) # right half tree[node] = tree[2 * node] + tree[2 * node + 1]a = [1, 3, 5, 7, 9, 11, 13, 15]tree = [0] * (4 * len(a)) # 32 slots, root at 1build(a, tree, 1, 0, len(a) - 1)print(tree[1]) # 64print(tree[1:16]) # all 15 nodes- Time
- O(n)
- Space
- O(n)
- nodes
- 2n - 1 = 15
- array slots
- 4n = 32 (safe)
- vs prefix sums
- also O(n)
Build is a post-order recursion: leaves first, then each parent from its two children. Write the merge in exactly one place so build, query and update can never disagree.
In the real world
The same segment tree doing real jobs. Pick one and step through it.
Six employees with revenues 1, 3, 5, 7, 9 and 11 (in millions). Team leads, two VPs and the CEO each know the total for the people under them.
Step 1 of 7
Six employees
- 10
- 31
- 52
- 73
- 94
- 115
Revenues in millions: [1, 3, 5, 7, 9, 11]. Asking every employee for a figure is the plain loop: O(n) per question.
Step 1: Six employees
revenue = [1, 3, 5, 7, 9, 11] # six employees, in millionstree = [0] * (4 * len(revenue))def build(node, lo, hi): if lo == hi: tree[node] = revenue[lo]; return mid = (lo + hi) // 2 build(2 * node, lo, mid); build(2 * node + 1, mid + 1, hi) tree[node] = tree[2 * node] + tree[2 * node + 1]def query(node, lo, hi, l, r): if r < lo or hi < l: return 0 if l <= lo and hi <= r: return tree[node] mid = (lo + hi) // 2 return query(2 * node, lo, mid, l, r) + query(2 * node + 1, mid + 1, hi, l, r)def update(node, lo, hi, i, v): if lo == hi: tree[node] = v; return mid = (lo + hi) // 2 if i <= mid: update(2 * node, lo, mid, i, v) else: update(2 * node + 1, mid + 1, hi, i, v) tree[node] = tree[2 * node] + tree[2 * node + 1]build(1, 0, 5)print(tree[1], tree[2]) # 36 (CEO), 9 (VP West)print(query(1, 0, 5, 1, 4)) # 24update(1, 0, 5, 2, 10) # employee 2 gets a raise: 5 -> 10print(tree[1]) # 41Common mistakes
The bugs interviewers watch for, with the fix beside each.
Allocating only 2n slots
criticalWith root at 1 and children at 2k and 2k + 1, a non-power-of-two n leaves gaps, so indexes can exceed 2n. For n = 6 the largest slot is 13 and for n = 100 it is 253. 4n is always enough.
Wrongtree = [0] * (2 * n) # IndexError for n = 6Righttree = [0] * (4 * n) # always enough for the recursive layoutForgetting to recompute the parent
criticalAfter updating a child, every ancestor still holds the old total. Queries then mix new leaves with stale parents and return wrong sums.
Wrongif idx <= mid: update(2 * node, lo, mid, idx, val)else: update(2 * node + 1, mid + 1, hi, idx, val)# parent left staleRightif idx <= mid: update(2 * node, lo, mid, idx, val)else: update(2 * node + 1, mid + 1, hi, idx, val)tree[node] = tree[2 * node] + tree[2 * node + 1]Wrong identity on no overlap
criticalThe no-overlap return value must not change the answer. 0 is right for sum but wrong for min (it beats every positive value). Use infinity for min, minus infinity for max.
Wrongif r < lo or hi < l: return 0 # range MIN queryRightif r < lo or hi < l: return float("inf") # identity for minMixing inclusive and exclusive ranges
majorThis code treats [l, r] as inclusive at both ends. Passing r - 1 or n instead of n - 1 silently drops or adds an element.
Wrongquery(tree, 1, 0, n, l, r - 1) # mixed conventionsRightquery(tree, 1, 0, n - 1, l, r) # inclusive everywhereSplitting at different midpoints
majorBuild, query and update must cut every range at the same mid. If one uses (lo + hi + 1) // 2, it looks for children that hold different ranges and reads the wrong values.
Wrongmid = (lo + hi + 1) // 2 # in query onlyRightmid = (lo + hi) // 2 # the same line in build, query and updatePassing a delta where a value is expected
minorThis update sets the leaf to val. Passing the difference (+5) turns a[2] into 5 instead of 10. Decide whether update means set or add, and name it that way.
Wrongupdate(tree, 1, 0, n - 1, 2, 10 - a[2]) # sets leaf to 5Rightupdate(tree, 1, 0, n - 1, 2, 10) # set a[2] = 10
Interview tips
How to explain it
- Each node stores the merge (sum, min, max) of one range; children split it at mid.
- Query: no overlap returns the identity, full overlap returns the node, partial overlap asks both children.
- Update: one root-to-leaf path, then recompute each ancestor. Both are O(log n); build is O(n).
Spot it in the wild
- Many range queries mixed with point updates on the same array.
- Range min or max with updates, where prefix sums do not apply.
- Range updates plus range queries: add lazy propagation.
Memory tricks
- BLUR: Build bottom-up, Left 2i and right 2i + 1, Update leaf to root, Range query combines pieces.
- None, all, some: return identity, return node, recurse.
- Four n slots, four nodes per level, log n levels.
Watch out
- Allocate 4n for the recursive layout.
- Change the merge and the identity together.
- Keep one range convention: inclusive [l, r] everywhere.