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)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…
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.
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.
def segment_range_query(values, queries):
return [sum(values[left:right + 1]) for left, right in queries]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.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
def segment_range_query(values, queries):
return [sum(values[left:right + 1]) for left, right in queries]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.
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 resultsImplement 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.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
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 resultsUse 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. |
| 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 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.
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 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)Interview bounds depend on the stated representation, input model, and real Python operations.
| Operation | Average | Worst | Interview note |
|---|---|---|---|
| Direct static boundary Lab | O(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 operations | O(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. |
O(n + q) for direct static boundary lab; O(n + m) for build and process m tree operations.
These are the mistakes most likely to survive a happy-path example and fail a boundary case.
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.
total = sum(values[left:right])total = sum(values[left:right + 1])Where you will hit this: Maintain Segment-Tree Range Sums(opens in a new tab)
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.
tree[index] = valuetree[index] = value
while index > 1:
index //= 2
tree[index] = tree[2 * index] + tree[2 * index + 1]Where you will hit this: Maintain Segment-Tree Range Sums(opens in a new tab)
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.
total = 1
for value in contributions:
total += valuetotal = 0
for value in contributions:
total += valueWhere you will hit this: K-Radius Subarray Averages(opens in a new tab)
Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.
python-docs · checked 2026-07-27