All algorithms
Trees

Segment Tree

Range queries and point updates in O(log n) on an array-shaped tree.

TimeO(log n) per querySpaceO(n)CategoryTrees

A segment tree stores an aggregate (sum, min, max…) for every range in a balanced binary tree flattened into an array: node 1 covers the whole array, node 2i its left half and node 2i+1 its right half. A range query descends and combines only the O(log n) nodes that fully fit inside it.

It is the standard answer to 'answer many range queries while the array keeps changing' — prefix sums are faster to build but cannot survive updates.

The three query cases (no overlap, full overlap, partial overlap) are what make it click. AlgoLens renders the tree from the flat array, so you can see which nodes a query actually touches and which whole subtrees it skips.

The code

segment_tree.cpp
#include <bits/stdc++.h>
using namespace std;

int a[6] = {1, 3, 5, 7, 9, 11};
int tree[24];

void build(int node, int lo, int hi) {
    if (lo == hi) {
        tree[node] = a[lo];
        return;
    }
    int mid = (lo + hi) / 2;
    build(node * 2, lo, mid);
    build(node * 2 + 1, mid + 1, hi);
    tree[node] = tree[node * 2] + tree[node * 2 + 1];
}

int query(int node, int lo, int hi, int l, int r) {
    if (r < lo || hi < l) return 0;
    if (l <= lo && hi <= r) return tree[node];
    int mid = (lo + hi) / 2;
    return query(node * 2, lo, mid, l, r) + query(node * 2 + 1, mid + 1, hi, l, r);
}

int main() {
    build(1, 0, 5);
    cout << query(1, 0, 5, 1, 4) << '\n';
    return 0;
}
Open this in the visualizer

Now run your own Segment Tree

AlgoLens traces your code — arrays, graphs, trees and recursion — from a real execution, so you see how it actually behaves, not a canned animation.

Paste your code

Keep going