progress

~/problems / Range queries / Segment tree (+ lazy propagation)

Build and update a bottom-up segment tree

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

The short way to write a segment tree is a flat list tree of length 2n: leaves tree[n .. 2n-1] copy nums; each internal node i (from n - 1 down to 1) holds tree[2i] + tree[2i + 1]; tree[0] stays 0, and tree[1] is the total.

Write the two operations everything else builds on:

  • build(nums) -> list[int]: that list of length 2 * len(nums).
  • update(tree, i, value) -> None: set original position i (0-based) to value in place and fix every ancestor.
tree = build([5, 3, 2, 7])
# [0, 17, 8, 9, 5, 3, 2, 7]
#     ^root ^  ^  leaves...
update(tree, 1, 10)
# tree == [0, 24, 15, 9, 5, 10, 2, 7]
The flat list [0, 24, 15, 9, 5, 10, 2, 7] after the update, drawn as a tree where node i has children 2i and 2i + 1 and the leaves at indexes 4 to 7 are nums; setting position 1 to 10 rewrote leaf 5, then nodes 2 and 1.
The tree after update(tree, 1, 10).

Up to 10**5 values, possibly negative; n needn't be a power of two.

⭐ Bonus: rebuilding the whole tree on each update still passes; a speed test with 50,000 updates earns a star if update only touches the O(log n) nodes on the way up.

Show hint

node i's parent is i // 2: after writing leaf n + i, walk i //= 2 to the root, recomputing each node from its children.

Topic: Segment tree (+ lazy propagation). Any associative range query with point or range updates in O(log n).

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc