Skip to the workspace
Pebellslearn by building
Prefix Sums & Range Queries  ›  Lesson

Segment Trees & Lazy Propagation

Segment Trees & Lazy Propagation 40 minAnswer any combinable range question from the few nodes that fit inside it, and defer range updates with tags

dsa / Segment Trees & Lazy Propagation

Explore each scene at your own pace.

01 · The shape

The shape

Segment Trees & Lazy Propagation

Definition
A segment tree is a binary tree in which each node stores a combined answer, such as a sum or a minimum, for a range of the array, so range queries and updates take O(log n). Lazy propagation delays range updates by leaving pending tags on nodes.
In plain words
It is a tournament bracket for ranges. Each node already knows the winner, say the lowest value, of its stretch, so a query only collects a few ready-made answers. Lazy tags are sticky notes saying apply this change later, when someone actually looks below.

In short: a segment tree stores one aggregate per node, built bottom-up from its two children, so a range query visits only nodes that are wholly inside the range (total cover), wholly outside (disjoint), or split between — about O(log n) nodes either way. It never subtracts, so it handles min, max, gcd, anything combinable from two halves, unlike a Fenwick tree. Lazy propagation extends it to range updates: a totally-covered node gets its value and a pending tag updated without visiting its children, and the tag is pushed down only right before something needs to read below it.

A segment tree query for min 1..6: node 4-7 is total cover and stops, node 0-1 is split into a disjoint leaf and an inside leaf

Quarry's latency panel doesn't want a total. It wants the fastest and slowest response between two minutes, while new measurements keep arriving. Every structure so far fails on that:

  • the prefix row and the Fenwick tree both answer a range as prefix minus prefix, and min can't be subtracted;
  • square-root blocks can do min, but only at O(√n).

A segment tree handles any aggregate you can combine from two halves: sum, min, max, gcd, "longest run of healthy minutes", in O(log n) per query and per edit. It needs no subtraction, only a way to merge a left answer with a right answer. Later in the lesson it learns to take range updates too, using lazy propagation.

The shape

The root owns the whole log, minutes 0..n−1. Each node splits its range in half and hands one half to each child, down to leaves that own one minute each. Every node stores the aggregate of its range, computed from its two children. There are about 2n nodes and the height is about log₂ n.

A query for l..r starts at the root. At every node it meets, exactly one of three things is true:

  • total cover: the node's range lies inside l..r. Use its stored value and stop.
  • disjoint: no overlap at all. Contribute nothing and stop.
  • partial: some overlap. Ask both children and combine their answers.

Here's the minimum over minutes 1..6, with the three outcomes in three colours. Badges show each node's stored minimum:

watch it move · tree

A range query visits a few nodes per level. Green nodes are wholly inside the range and answer for everything beneath them. Grey ones don't overlap, so they're skipped with everything beneath them. Only the partly covered ones go deeper.

The log is 5, 2, 7, 1, 3, 4, 6, 2. Every node's badge is the minimum of its range, built bottom-up from its children. Binary tree, 15 nodes, height 4.

1 / 17

Why only a few nodes per level? The range is contiguous, so on any level at most two nodes are partial: the ones containing its left edge and its right edge. Every other node there is wholly in or wholly out, and stops. So a query visits at most about four nodes per level, which is O(log n) in all.

Scene 1 of 7
Project context and further resources
You're building a piece ofQuarry — the analytics engine
This piece — segment_log(): Minimum over any range with edits — the aggregate a prefix row cannot subtract.
Scenario Quarry's latency panel shows the fastest response in any window while new measurements keep landing. The minimum can't be subtracted, so the engine keeps a segment tree and assembles each window from the nodes that fit inside it.
segment_log.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
segment_log(values, ops) → listAnswers to the min ops, with set ops applied in between.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.