CodeBlanks Logo Icon CodeBlanks

Segment tree

Segment tree answers range queries.

Segment tree

A segment tree enables range queries (sum, min, max) on an array. It is built in O(n) space; queries answer in O(log n) time.

For array [1, 3, 5, 7], the sum segment tree has root 16, left 4, right 12 as a 7-node tree.

Tree construction

The segment tree is represented as an array: tree[1] is root, tree[2i] and tree[2i+1] are left/right children. Leaves are the array itself.

Construction places leaves at the end and fills inner nodes as the sum of their children.

Practice build_segment_tree function

Write build_segment_tree(arr). Build the tree array: place leaves at the end, fill inner nodes with child sums. Print it with print(build_segment_tree([1, 3, 5, 7])).

Starter code

solution.py
def build_segment_tree(arr):
    # Build segment tree

Sample solution

solution.py
def build_segment_tree(arr):
    # Build segment tree
    n = len(arr)
    tree = [0] * (2 * n)
    for i in range(n):
        tree[n + i] = arr[i]
    for i in range(n - 1, 0, -1):
        tree[i] = tree[2 * i] + tree[2 * i + 1]
    return tree
print(build_segment_tree([1, 3, 5, 7]))

Expected output

[0, 16, 4, 12, 1, 3, 5, 7]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Segment tree: match the terms

Term Meaning
tree[1] 16 (sum)
tree[2] 4 (left)
tree[3] 12 (right)
tree[4] 1 (leaf)

2 What is the segment tree root for [1, 3, 5, 7]?

  • 4
  • 7
  • 16 Correct answer
  • 12

Explanation: Root is the sum of all elements: 1+3+5+7=16.

3 Inner node computation

Question
tree[i] = tree[2*i] + tree[____*i+1]
Answer
tree[i] = tree[2*i] + tree[2*i+1]

Explanation: 2 is right.

All lessons in Advanced