Skip to contentKEEP THE CRAFTTHE SANCTUARY

Segment Tree

A segment tree caches aggregates so range queries reuse disjoint contributions and point changes repair ancestors. Separate the direct-sum boundary baseline from the actual compact sum tree, convert inclusive bounds once, and preserve the combine identity.

1 practice exercise2 interview problems

Recognize it when Point values change while many range aggregates are requested.

Checking your account…

Segment Tree Code Labs

Nodes Own Explicit Ranges

A conventional segment tree divides the input into contiguous intervals and caches one aggregate per interval. Leaves hold individual elements, and parents combine child results. Associativity permits regrouping; an identity such as 0 for sum leaves a disjoint contribution neutral. First establish the query boundary contract, then add cached state only when repeated queries or updates justify it.

Build and Query Disjoint Cover

A cached range query selects disjoint contributions covering exactly the requested interval. A standard balanced segment tree takes O(log n) query operations. The first Lab below is deliberately a direct-sum boundary baseline: its actual reference code slices and sums the requested values, so one query costs O(range length) time and temporary slice space. It teaches inclusive endpoints and ownership before the second Lab introduces the tree.

Query Static Segment Ranges

Reference
def segment_range_query(values, queries):
    return [sum(values[left:right + 1]) for left, right in queries]
Practice

Implement segment_range_query(values, queries). Return the inclusive sum for each [left, right] query without mutating values. Every query satisfies 0 <= left <= right < len(values); empty values accepts only empty queries.

Public tests

  • Verify inclusive query boundaries

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Query Static Segment Ranges

def segment_range_query(values, queries):
    return [sum(values[left:right + 1]) for left, right in queries]

Propagate Point Updates

The second Lab builds a compact 2n array with leaves at n+i. Change a leaf and recompute every ancestor on its path; only O(log n) caches change. Its parent rule is the sum of its children. Without power-of-two padding, some internal groups wrap the original leaf order, so do not read arbitrary array nodes as textbook intervals. The boundary walk still chooses the correct disjoint sum contributions. General order-sensitive combines need an order-preserving layout and query accumulators; this Lab teaches sums.

Maintain Segment-Tree Range Sums

Reference
def segment_tree_ranges(values, operations):
    size = len(values)
    tree = [0] * (2 * size)
    tree[size:] = values
    for index in range(size - 1, 0, -1):
        tree[index] = tree[2 * index] + tree[2 * index + 1]
    def range_sum(left, right):
        left += size
        right += size + 1
        total = 0
        while left < right:
            if left % 2:
                total += tree[left]
                left += 1
            if right % 2:
                right -= 1
                total += tree[right]
            left //= 2
            right //= 2
        return total
    def update(index, value):
        index += size
        tree[index] = value
        while index > 1:
            index //= 2
            tree[index] = tree[2 * index] + tree[2 * index + 1]
    results = []
    for operation in operations:
        if operation[0] == "sum":
            results.append(range_sum(operation[1], operation[2]))
        elif operation[0] == "update":
            update(operation[1], operation[2])
    return results
Practice

Implement segment_tree_ranges(values, operations). Operations are ["sum", left, right] with inclusive bounds or ["update", index, value]. Return one number per sum operation and do not mutate values. Sum bounds satisfy 0 <= left <= right < len(values); update indices satisfy 0 <= index < len(values). Empty values accepts only empty operations.

Public tests

  • Verify Maintain Segment-Tree Range Sums behavior

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Maintain Segment-Tree Range Sums

def segment_tree_ranges(values, operations):
    size = len(values)
    tree = [0] * (2 * size)
    tree[size:] = values
    for index in range(size - 1, 0, -1):
        tree[index] = tree[2 * index] + tree[2 * index + 1]
    def range_sum(left, right):
        left += size
        right += size + 1
        total = 0
        while left < right:
            if left % 2:
                total += tree[left]
                left += 1
            if right % 2:
                right -= 1
                total += tree[right]
            left //= 2
            right //= 2
        return total
    def update(index, value):
        index += size
        tree[index] = value
        while index > 1:
            index //= 2
            tree[index] = tree[2 * index] + tree[2 * index + 1]
    results = []
    for operation in operations:
        if operation[0] == "sum":
            results.append(range_sum(operation[1], operation[2]))
        elif operation[0] == "update":
            update(operation[1], operation[2])
    return results

Trace Inclusive Bounds and Ancestor Repair

Use the actual point-update Lab with four leaves. The first inclusive query reads leaves at indices 1 and 2; replacing leaf 2 must repair its parent and root before a full-range query can see the new total.

print(segment_tree_ranges([2, 4, 1, 3], [['sum', 1, 2], ['update', 2, 7], ['sum', 0, 3]])) followed by print(segment_tree_ranges([], []))

Step Executed statement State Why
1 tree[size:] = values; tree[index] = tree[2 * index] + tree[2 * index + 1] size = 4; tree = [0, 10, 6, 4, 2, 4, 1, 3] Bottom-up construction makes each parent sum available before the root.
2 left += size; right += size + 1; total = 0 query [1, 2]: left = 5; right = 7; total = 0 The extra one turns the inclusive end into a half-open boundary.
3 total += tree[left]; left += 1; right -= 1; total += tree[right] take tree[5] = 4 and tree[6] = 1; total = 5 Odd boundary slots supply exactly the two uncovered leaf contributions.
4 left //= 2; right //= 2; return total left = right = 3; first query result = 5 Equal boundaries mean no uncovered segment remains.
5 index += size; tree[index] = value update index 2: tree[6] = 7 The leaf is assigned a replacement value while ancestors are temporarily stale.
6 index //= 2; tree[index] = tree[2 * index] + tree[2 * index + 1] tree[3] = 10; then tree[1] = 16 Repairing both ancestors restores the cache invariant.
7 results.append(range_sum(operation[1], operation[2])); return results full query [0, 3] selects tree[1] = 16; result = [5, 16] The second query’s boundary walk selects the repaired root sum; appending that returned sum preserves the earlier result.
Print Output
1 [5, 16]
2 []

The update is assignment, not addition. Only caches on the modified leaf’s ancestor path change, and later sums can reuse those repaired caches. The direct-slice first Lab has the same answers but a different cost and no cached state.

Choose Segment Tree or Fenwick Tree

Choose a segment tree when the combine is an arbitrary associative operation or the problem needs richer range updates. Choose a Fenwick tree for compact point-update and prefix-sum workflows. With immutable data, a prefix array is usually simpler than either structure.

Explain It in an Interview

Say: “Each node caches the aggregate for an explicit range. A query decomposes its target into disjoint cached ranges; a point update repairs exactly one root path.” Name the combine and identity, state O(n) build, O(log n) query/update, and O(n) space. The Python list reference(opens in a new tab) covers the array representation.

Maintain Segment-Tree Range Sums(opens in a new tab) turns both query and update invariants into an executable trace.

Python Version Note

Python 3.11+

The examples use standard Python containers and syntax available in the supported browser runtime; Segment Tree itself is taught as an interview abstraction.

Verify in Python docs(opens in a new tab)

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Direct static boundary LabO(sum(query lengths))O(q * n)q queries; sum(values[left:right+1]) copies each slice and scans it. Peak temporary slice can contain n values, plus returned results.
Build and process m tree operationsO(n + m * log(n + 1))O(n + m * log(n + 1))Valid query/update indices with constant-cost numeric addition; linear build, logarithmic query/update, and returned query results.

Space

O(n + q) for direct static boundary lab; O(n + m) for build and process m tree operations.

Assumptions

  • q queries; sum(values[left:right+1]) copies each slice and scans it. Peak temporary slice can contain n values, plus returned results.
  • Valid query/update indices with constant-cost numeric addition; linear build, logarithmic query/update, and returned query results.

Invariants Worth Saying Aloud

  1. Every internal cache equals the sum of its descendant leaf values.
  2. A point assignment repairs all affected ancestor caches before a later query.
  3. Public inclusive [left, right] becomes an internal half-open walk by adding one to right.

When To Use Or Avoid Segment Tree

Use It When

  • Use cached range state when repeated updates rule out a static prefix array.
  • Choose a segment tree when range combines need more than prefix subtraction.

Choose Another Tool When

  • Use prefix sums for immutable range-sum data.
  • Do not infer lazy range updates or a fully general noncommutative combine from these sum-only Labs.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Dropping the inclusive right endpoint

Python slicing excludes its stop. Using right directly omits a value promised by the inclusive contract.

Prevent it: Convert inclusive right to the exclusive boundary right+1 once.

Avoid

total = sum(values[left:right])

Use instead

total = sum(values[left:right + 1])

Updating the leaf while leaving ancestor sums stale

A cached whole-range result still reads the old root unless the changed leaf's ancestors are repaired.

Prevent it: Recompute every parent on the leaf-to-root path.

Avoid

tree[index] = value

Use instead

tree[index] = value
while index > 1:
    index //= 2
    tree[index] = tree[2 * index] + tree[2 * index + 1]

Using a non-neutral starting value for a sum

Starting at one adds a contribution that belongs to no selected segment.

Prevent it: Use zero as the sum identity and add each selected contribution exactly once.

Avoid

total = 1
for value in contributions:
    total += value

Use instead

total = 0
for value in contributions:
    total += value

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.