cconnected.
Understand the pattern. Find your own way.Find your starting point
Your learning feed/Idea 60 of 218
Ideas this builds on
Range queries60 / 218

Segment tree: combine range summaries

Picture

To sum positions 2..6, combine a few tree nodes whose intervals exactly cover that range.

Predict

Why must the combine operation be associative?

Walk through the small example

Grouping tree pieces must not change meaning. A range can be decomposed into O(log n) stored interval summaries.

Mental model and complete Python solution

The tree stores answers for carefully chosen intervals. A query gathers disjoint pieces; an update changes one leaf and only the summaries on its path to the root.

What the function promises: SegmentSum supports zero-based point assignment and half-open range sums [left,right).

class SegmentSum:
    def __init__(self, values):
        size = 1
        while size < len(values): size *= 2
        self.size, self.tree = size, [0] * (2 * size)
        self.tree[size:size + len(values)] = values
        for i in range(size - 1, 0, -1):
            self.tree[i] = self.tree[2*i] + self.tree[2*i+1]
    def set(self, index, value):
        i = self.size + index
        self.tree[i] = value
        i //= 2
        while i:
            self.tree[i] = self.tree[2*i] + self.tree[2*i+1]
            i //= 2
    def query(self, left, right):
        total = 0
        left += self.size; right += self.size
        while left < right:
            if left & 1: total += self.tree[left]; left += 1
            if right & 1: right -= 1; total += self.tree[right]
            left //= 2; right //= 2
        return total

tree = SegmentSum([2,1,3,4])
assert tree.query(1,4) == 8
tree.set(1,5)
assert tree.query(1,4) == 12

Work and storage: Build O(n), point assignment and range query O(log n), storage O(n).

When to recognize it: A range can be decomposed into O(log n) stored interval summaries.

Check before applying it: Non-associative operations cannot be regrouped arbitrarily; lazy range updates need a compatible composition rule.

Change one rule

Add a value to every point in a range.

See what changes

Use lazy propagation: store a pending update at a covered node and push it only when children are needed.

Connect

tree summaries: Each parent is a reusable summary of its children.

Fenwick tree: prefix sums with updates: Fenwick is smaller and simpler for invertible prefix operations.