Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Algorithm · Data Structures

Ranges in Log Time.

Watch the explainer

Don't memorize the segment tree — watch it answer ranges in log time. Prefix sums give O(1) range queries but choke on updates. A segment tree fixes that: each node stores the sum of an interval, so a range query combines just a handful of covering nodes in O(log n) — and changing one value fixes a single leaf and ripples up to the root, also O(log n).

interval sums · range query · point update · O(log n)
NODE = INTERVAL

Every node stores the sum of a contiguous slice of the array.

LEAVES

The array elements themselves — the base of the tree.

QUERY

Combine the few nodes that fully cover the range — O(log n).

UPDATE

Change a leaf, recompute its ancestors up to the root — O(log n).

segment-tree.sim — array [2,1,5,3] · build · query · update
Ready

Leaves hold the array [2,1,5,3]; each parent stores the sum of its interval. Press Step to build the tree bottom-up, then answer a range query, then update a value and watch it ripple to the root.

Build
Phase
—
Result

Precompute the pieces, combine on demand

A prefix-sum array is unbeatable for range sums until a value changes — then every prefix after it is wrong, an O(n) repair. The segment tree trades that O(1) query for a still-fast O(log n) query in exchange for O(log n) updates, by storing partial sums at many granularities. No single node covers your exact range, but a logarithmic number of them tile it perfectly, and any single element sits under only a logarithmic number of nodes.

01

Build bottom-up

Leaves are the elements; each internal node is the sum of its two children. Building the whole tree is O(n).

02

Query a range

Walk down from the root: take a whole node if its interval lies inside the query, recurse where it partially overlaps. About 2 log n nodes.

03

Update a point

Change the leaf, then recompute each ancestor from its children up to the root — only log n nodes change.

04

Range updates

Lazy propagation defers pushing an update to children until needed, giving O(log n) range updates too.

Build
O(n)
Range query
O(log n)
Point update
O(log n)
Space
O(n)

The same tree works for any associative combine — swap sum for min, max, or gcd and you get range-min or range-gcd queries for free. Lighter alternatives exist: a Fenwick (binary indexed) tree does range-sum with updates in a few lines and less memory, while a prefix-sum array wins only when the data never changes.

Check yourself

1 · What does each internal node of a segment tree store?

Internal nodes hold the combination of their children, so they summarize a whole interval of the array.

2 · Why can a segment tree update a value in O(log n)?

A single element sits under a logarithmic number of nodes, so only those ancestors need recomputing.

3 · Compared to a prefix-sum array, a segment tree is better when…

Prefix sums give O(1) queries but O(n) updates; the segment tree keeps updates fast (O(log n)) for mutable data.

The picture: a query made of whole blocks

2571451293127613253701234567query [2..6] = 5 + 12 + 7 = 24, from 3 nodes instead of 5 leaves
A segment tree over [2, 5, 1, 4, 9, 3, 7, 6]. Each node stores the sum of its interval. The query for indices 2 to 6 is answered by the three highlighted nodes, with no leaf-by-leaf addition.

Worked example, step by step

Take [2, 5, 1, 4, 9, 3, 7, 6] (8 leaves, so the tree has 15 nodes) and ask for the sum of indices 2 to 6, whose true answer is 24. Start at the root and, for each node, classify its interval against the query: outside (skip), inside (take the stored sum) or partial (recurse). Each row is one node visited.

Node intervalVersus [2..6]ActionAddsTotal so far
[0..7]partialrecurse into both halves—0
[0..3]partialrecurse into both halves—0
[0..1]outsideskip00
[2..3]insidetake node = 5+55
[4..7]partialrecurse into both halves—5
[4..5]insidetake node = 12+1217
[6..7]partialrecurse into both halves—17
[6..6]insidetake node = 7+724
[7..7]outsideskip024

The query touched 9 nodes but added only 3 numbers (5 + 12 + 7), instead of the 5 elements in the range. Every partial node splits into two children, and at most two nodes per level can be partial, one at each end of the range, which is the whole reason the bound is logarithmic. A point update works in reverse: change the leaf, then recompute only its ancestors. Changing index 4 from 9 to 10 rewrites 4 nodes (the leaf, [4..5], [4..7] and the root) and leaves the other 11 alone.

Complexity and trade-offs

CaseTimeSpaceWhy
Segment treebuild O(n), query and update O(log n)O(n)At most two partial nodes per level. Measured: over all 32,896 ranges of a 256-element array the busiest query visited 31 nodes (about 4 · log₂ 256 = 32).
Prefix-sum arraybuild O(n), query O(1), update O(n)O(n)Unbeatable when nothing changes; changing index 0 rewrites all 8 prefix entries.
Plain array, no structurequery O(n), update O(1)O(n)Adds the range every time. Fine for a few queries, ruinous for many.
Fenwick (binary indexed) treequery and update O(log n)O(n)Shorter code and smaller constants, but it relies on an invertible operation like sum; min and max over arbitrary ranges are awkward.
Square-root decompositionquery and update O(√n)O(n)Simpler to write, but √n grows much faster than log n.

The segment tree is the most general of these: any associative combine works, and with lazy propagation it also does range updates in O(log n). You pay in memory (a recursive layout with 1-indexed children needs up to 4n slots, an iterative bottom-up one needs 2n) and in constant factors compared with a Fenwick tree. Choose by the operation: invertible sums with point updates favour a Fenwick tree, static data favours prefix sums, and everything else (min, max, gcd, range assignment) favours a segment tree.

Common mistakes

  • Allocating only 2n for the recursive layout

    With children at 2i and 2i + 1 and arbitrary n, the largest index used can exceed 2n: for n = 6 it reaches 13 against an array of 12, and this is the smallest n where it happens. Allocate 4n, or use the bottom-up layout where 2n is exact.

  • Mixing inclusive and exclusive bounds

    The bottom-up query wants a half-open [l + n, r + n + 1). Forgetting the + 1 on [1, 3] over [1, 2, 3, 4, 5] returns 5 instead of 9, silently dropping the last element.

  • Updating the leaf but not the ancestors

    Setting index 2 of [1, 2, 3, 4, 5] to 10 without climbing to the root leaves every node above the leaf stale. The query for [1, 3] that should return 16 returns 9. Walk i //= 2 to the root, recomputing each parent from its two children.

  • Assuming the combine commutes

    Sum and min can be accumulated in any order. String concatenation, matrix product and function composition cannot. Over "abcdefgh", a bottom-up query for indices 1 to 6 that appends blocks as it meets them returns bgcdef instead of bcdefg. Keep a left accumulator and a right accumulator, and join them at the end.

  • Forgetting the length in lazy range-add

    Adding v to every element of a range of length len raises a node’s sum by v · len, not by v. Adding 10 to the first four of [1, …, 8] should move that block’s sum from 10 to 50; without the factor you get 20.

Where this shows up

  • Range-minimum and range-maximum queries

    The same tree with min as the combine answers “lowest value in this window” while the data keeps changing, which is the standard tool in competitive programming for mutable range queries.

  • Sweep-line geometry

    Computing the area covered by a union of rectangles sweeps across the plane while a segment tree over the y-axis tracks how much of the line is currently covered, with each rectangle edge as a range update.

  • Order statistics and “first position where”

    Because every node knows its subtree’s total, you can descend from the root to find the first index whose prefix sum reaches a target, or the k-th present element, in O(log n) with no search over the array.

  • Live aggregates over changing data

    Anything shaped like “aggregate over a range while single values are overwritten” maps onto it: scores in a range of leaderboard ranks, resource counts across a span of slots, or the busiest second inside a time window.

SOLVE IT YOURSELF

Solve it: range queries with updates

Store the array in the leaves and every partial sum in the nodes above. Then any range, however awkward, is a handful of precomputed blocks. Python or TypeScript, running for real in your browser.

YOUR TASK

Implement an iterative segment tree over an array of size n, stored in a flat array of size 2n: build from the input, update(i, val) to set a position, and range_sum(lo, hi) over an inclusive range. All in O(log n).

HINTS — 6 IDEAS
  1. Layout: leaf i lives at tree[n + i], and every internal node i holds tree[2i] + tree[2i+1].
  2. Build by filling the leaves, then walking i from n − 1 down to 1 — children are always at higher indices, so one backwards pass is enough.
  3. Update a leaf, then walk to the root with i //= 2, recomputing each parent from its two children.
  4. Query iteratively: convert to [lo + n, hi + n + 1), then climb. If lo is a right child (odd) it is not fully inside its parent — take it and step right. Mirror for hi.
  5. Halve both bounds each round. The loop ends when they meet, having covered the range in at most 2·log n blocks.
  6. The half-open hi + 1 conversion is what makes the odd/even test work — mixing inclusive and exclusive here is the classic off-by-one.
CPython · WebAssembly

Questions

How much memory does a segment tree use?

About 2n to 4n nodes for an array of n elements (a common safe allocation is 4n). Each node stores one aggregate value, so it is O(n) space overall.

What is lazy propagation?

A technique for range updates: instead of updating every affected leaf, you mark a node as "pending +x for my whole interval" and only push that down to children when a later query or update needs to descend. It keeps range updates at O(log n).

When would I pick a Fenwick tree instead?

When you only need prefix or range sums with point updates, a Fenwick (binary indexed) tree is shorter to write and uses less memory. Reach for a segment tree when you need range updates, non-sum operations, or more flexibility.

Both ways, in log time.

Store interval sums in a tree and range queries and point updates both cost O(log n). The mutable cousin of the prefix sum.

▶  Watch it explained

Segment Tree: Time and Space Complexity, From First Principles

Finished this one? 0 / 99 Algorithms done
NextLazy Segment Tree: Update Lazily Next on the “Answering a range in log time” ladder · rung 4 of 7

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms