Python 3D Academyবাংলা

Segment tree: the best of any range, kept up to date

🌍 In real life. A cricket board keeps a knockout bracket on the wall: every match result is written in, so "who is the strongest of players 3 to 6?" can be answered from a few boxes already filled in, without replaying anything. When one player's score is corrected, only the boxes on that player's path to the final change.

The last lesson's Fenwick tree adds and takes away prefix sums. The maximum (or minimum) of a range can't be found by taking one prefix away from another, so it needs this bracket: a segment tree.

The idea in one sentence: a segment tree is a binary tree in which every node stores the answer (here the maximum) for one range of the list, split in half at each level, so any range is covered by O(log n) whole nodes and a change touches only the O(log n) nodes above one leaf.

Its words:

  • node and range: node k covers lo..hi; its children cover lo..mid and mid + 1..hi
  • leaf: a node covering one position
  • array layout: like a heap (Chapter 49), node k's children are 2k and 2k + 1, with the root at 1; a list of 4n places is always enough
  • no overlap / fully inside / partly: the three cases a query meets at each node

Step by step, building it. Split the list in halves until single items, then let each pair "play a match": the parent keeps the larger. This is the knockout tournament of Lesson 42.3, with every result kept:

Asking about a range. For the maximum of positions 2 to 5, start at the root and at each node ask how its range meets the question:

  1. No overlap: the node's range is outside 2..5: it contributes nothing (-inf).
  2. Fully inside: its whole range is inside 2..5: its stored maximum is the answer for that part; don't go deeper.
  3. Partly: ask both children and keep the larger answer.

Watch the query use two stored boxes, 2..3 and 4..5, instead of four numbers:

Changing one position. Set the leaf, then walk back up its path, recomputing each parent as the larger of its two children: one node per level.

Why it is correct. Every node stores the maximum of exactly its range, which is true for leaves and stays true for a parent built from its two children. A query returns, for each node it stops at, either nothing (outside) or that range's maximum (inside), and the ranges where it stops cover l..r exactly once.

What it costs, by counting. The tree has about 2n nodes, built once: O(n). A query stops at no more than 2 "fully inside" nodes per level, and there are log₂ n levels: O(log n). An update changes one node per level: O(log n). The same tree works for sums, minimums, or any operation where combining two answers gives the answer for both parts.

def build(nums, tree, node, lo, hi):
    if lo == hi:
        tree[node] = nums[lo]
        return
    mid = (lo + hi) // 2
    build(nums, tree, 2 * node, lo, mid)
    build(nums, tree, 2 * node + 1, mid + 1, hi)
    tree[node] = max(tree[2 * node], tree[2 * node + 1])


def query(tree, node, lo, hi, l, r):
    if r < lo or hi < l:                    # no overlap
        return float("-inf")
    if l <= lo and hi <= r:                 # fully inside
        return tree[node]
    mid = (lo + hi) // 2                    # partly: ask both children
    return max(query(tree, 2 * node, lo, mid, l, r),
               query(tree, 2 * node + 1, mid + 1, hi, l, r))


def update(tree, node, lo, hi, i, value):
    if lo == hi:
        tree[node] = value
        return
    mid = (lo + hi) // 2
    if i <= mid:
        update(tree, 2 * node, lo, mid, i, value)
    else:
        update(tree, 2 * node + 1, mid + 1, hi, i, value)
    tree[node] = max(tree[2 * node], tree[2 * node + 1])


heights = [4, 7, 2, 6, 3, 8, 1, 5]
tree = [0] * (4 * len(heights))
build(heights, tree, 1, 0, len(heights) - 1)
print(query(tree, 1, 0, 7, 2, 5), query(tree, 1, 0, 7, 0, 2))
update(tree, 1, 0, 7, 2, 9)                # building 2 gets two new floors
print(query(tree, 1, 0, 7, 2, 5), query(tree, 1, 0, 7, 0, 2))
After the update only the nodes on position 2's path changed, and both queries see the new 9.

Mistakes and edge cases.

  • Mixing up "fully inside". It is l <= lo and hi <= r (the node's range inside the question), not the other way round; reversed, a big node answers for a small question.
  • The wrong "nothing". For a maximum the neutral answer is -inf, for a minimum inf, for a sum 0. Returning 0 for a maximum breaks lists of negative numbers.
  • A list that is too short. With 2 * n places the deepest nodes of an uneven tree can fall off the end: IndexError: list assignment index out of range. Use 4 * n.
  • Forgetting to fix the parents. An update that only sets the leaf leaves every box above it stale.
  • Reaching for it too soon. With no changes, a prefix-sum list (sums) or a sparse table is simpler; with only sums and changes, a Fenwick tree is shorter.

Quiz

  1. What does this print?

    def build(nums, tree, node, lo, hi):
        if lo == hi:
            tree[node] = nums[lo]
            return
        mid = (lo + hi) // 2
        build(nums, tree, 2 * node, lo, mid)
        build(nums, tree, 2 * node + 1, mid + 1, hi)
        tree[node] = max(tree[2 * node], tree[2 * node + 1])
    
    
    nums = [5, 1, 4, 2]
    tree = [0] * 16
    build(nums, tree, 1, 0, 3)
    print(tree[1], tree[2], tree[3])
  2. Why can't a Fenwick tree answer "the maximum of positions 3 to 6" the way it answers a range sum?

    • A range sum is one prefix minus another, but a maximum can't be taken away like that
    • Fenwick trees only hold whole numbers
    • The maximum needs O(n) memory
  3. A segment tree over 1,000,000 numbers. About how many nodes does one update change?

    • About 20: one per level
    • About 1,000: the square root
    • All of them
  4. For [4, 7, 2, 6, 3, 8, 1, 5], the maximum of positions 0 to 2 should be 7, but this answers 8. Which line is wrong?

    def query(tree, node, lo, hi, l, r):
        if r < lo or hi < l:
            return float("-inf")
        if lo <= l and r <= hi:
            return tree[node]
        mid = (lo + hi) // 2
        return max(query(tree, 2 * node, lo, mid, l, r),
                   query(tree, 2 * node + 1, mid + 1, hi, l, r))

Coding tasks

  1. build is done. Write query(tree, node, lo, hi, l, r): the maximum of positions l..r (both included), where node node covers lo..hi.

  2. Write update(tree, node, lo, hi, i, value): set position i to value and fix every node above it. (build and query are given.)