AlgoTales · Roadmap

Build

Intermediate · 10 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Building a segment tree means arranging a list into a pyramid where each node stores the answer (sum, minimum, maximum) for a stretch of the list. Pairs combine into bigger pairs until the top node holds the answer for everything.

Practical use cases

  • Web app: Daily sales dashboard for 100,000 products. A reporting page loads daily sales per product and lets the owner ask for totals or peaks over any product range. The server builds the pyramid once when data loads, taking a single pass, and every later question uses ready-made partial answers.
  • Web app: Monitoring chart service. A server-health page stores one CPU reading per second. Building the tree over the day's readings once lets the chart zoom in on any time window by combining a few stored blocks instead of re-reading thousands of values. Zooming into a ten-minute stretch feels the same as zooming into a whole day, since only a few blocks are combined.
  • System: Game engines and database indexes. Game engines build trees over objects or ranges for quick region questions, and databases use similar tree-shaped summaries so that queries need not scan everything. Building them once at load time is the price paid so that every later question can be answered almost instantly.

The story: The Diwali Donation Pyramid

Every Diwali the mohalla collects donations for lights and sweets. Eight families put money in eight envelopes, and Uncle Rakesh, the secretary, must answer questions all week: "How much from the first four families?" "From families 3 to 6?" "And when Zoya's family gives more, update it!" His running-total notebook broke every time an envelope changed.

Grandpa Bhaskar suggested a smarter notebook, shaped like a pyramid. "Ask two neighbours to pool their money and write the pair total on a card. Then ask two pair-cards to pool and write a total of four. Keep pooling until a single card at the top holds everything." Mira drew it as a tree: the eight envelopes at the bottom, four pair cards above them, two cards above those, and one root card at the very top.

The best part is how you build it: write a recursive rule. To make the card for a stretch, split the stretch in two halves, make both halves' cards first, then add them. If the stretch has just one family, the card is simply that family's envelope. Visit every card once and the whole pyramid is ready. This is a segment tree, and building it takes one trip.

How to spot this problem, and where you need it

You will ask many different range questions (sum, minimum, maximum) over the same list and need a structure prepared in advance that makes each of them fast.

Signs you need it

  • The feature offers arbitrary ranges chosen by the user and a loop per request is too slow.
  • The values may also change later, so a simple prefix list will not be enough.
  • The question is not only sums but also min, max or other combinable answers.
  • The problem says "segment tree" or "range query with updates".

Where to use it in a project

  • Data loading steps of dashboards that will answer many range questions.
  • Monitoring, trading or analytics backends that summarise time-series data.

The solution

Treat the list as the bottom row of a tree. Each parent stores the combined answer (sum, min or max) of its two children, and the root stores the answer for the whole list. Build it from the bottom up in one pass, filling each parent once its children are done. The tree has about twice as many nodes as the list has items.

Payoff: Before: nothing prepared, so each question loops over the data. After: one pass to build, then every range answer in about 20 steps.

Explain it like I am 8

Imagine a school sports day where each house adds its scores. Pairs of friends add their points, pairs of pairs add again, and finally the big scoreboard shows the grand total. Every circle in the tree is a mini-scoreboard for a group of neighbours, and the top one is for everybody.

How it works, step by step

  1. Start with the whole row (positions 0 to n-1). This will be the root of the tree.
  2. If there is only one item, the circle simply copies that item. This is the stopping point of the recursion.
  3. Otherwise split in the middle and build the left half and the right half, each as its own smaller tree.
  4. Combine: the circle for the stretch holds left total + right total (for other jobs, a minimum or a maximum).
  5. Store in an array. Number the root 1; the children of circle k are 2k and 2k + 1. Reserve room for about 4n circles to be safe.

The code in four languages

PHP

<?php
class SegTree {
    private array $t;       // t[1] is the root; children of k are 2k and 2k+1
    private int $n;

    public function __construct(array $a) {
        $this->n = count($a);
        $this->t = array_fill(0, 4 * $this->n, 0);
        $this->build($a, 1, 0, $this->n - 1);
    }

    // Make the card for positions l..r
    private function build(array $a, int $node, int $l, int $r): void {
        if ($l === $r) {                         // one family: copy the envelope
            $this->t[$node] = $a[$l];
            return;
        }
        $m = intdiv($l + $r, 2);                 // split in the middle
        $this->build($a, 2 * $node, $l, $m);     // left half first
        $this->build($a, 2 * $node + 1, $m + 1, $r);
        $this->t[$node] = $this->t[2 * $node] + $this->t[2 * $node + 1];   // pool both halves
    }

    public function cards(int $count): array {
        return array_slice($this->t, 1, $count);
    }
}

$donations = [5, 3, 7, 2, 6, 4, 1, 8];
$tree = new SegTree($donations);
// root, then level by level: 36 | 17 19 | 8 9 10 9 | the eight envelopes
echo implode(',', $tree->cards(15)) . PHP_EOL;

JavaScript

class SegTree {
  constructor(a) {
    this.n = a.length;
    this.t = new Array(4 * this.n).fill(0);   // t[1] is the root; children of k are 2k and 2k+1
    this.build(a, 1, 0, this.n - 1);
  }

  // Make the card for positions l..r
  build(a, node, l, r) {
    if (l === r) {                            // one family: copy the envelope
      this.t[node] = a[l];
      return;
    }
    const m = (l + r) >> 1;                   // split in the middle
    this.build(a, 2 * node, l, m);            // left half first
    this.build(a, 2 * node + 1, m + 1, r);
    this.t[node] = this.t[2 * node] + this.t[2 * node + 1];   // pool both halves
  }
}

const donations = [5, 3, 7, 2, 6, 4, 1, 8];
const tree = new SegTree(donations);
// root, then level by level: 36 | 17 19 | 8 9 10 9 | the eight envelopes
console.log(tree.t.slice(1, 16).join(','));

Java

import java.util.*;

public class Main {
    static class SegTree {
        int[] t;                    // t[1] is the root; children of k are 2k and 2k+1
        int n;

        SegTree(int[] a) {
            n = a.length;
            t = new int[4 * n];
            build(a, 1, 0, n - 1);
        }

        // Make the card for positions l..r
        void build(int[] a, int node, int l, int r) {
            if (l == r) {                           // one family: copy the envelope
                t[node] = a[l];
                return;
            }
            int m = (l + r) / 2;                    // split in the middle
            build(a, 2 * node, l, m);               // left half first
            build(a, 2 * node + 1, m + 1, r);
            t[node] = t[2 * node] + t[2 * node + 1];    // pool both halves
        }
    }

    public static void main(String[] args) {
        int[] donations = {5, 3, 7, 2, 6, 4, 1, 8};
        SegTree tree = new SegTree(donations);
        // root, then level by level: 36 | 17 19 | 8 9 10 9 | the eight envelopes
        System.out.println(Arrays.toString(Arrays.copyOfRange(tree.t, 1, 16)));
    }
}

Go

package main

import "fmt"

type SegTree struct {
	t []int // t[1] is the root; children of k are 2k and 2k+1
	n int
}

func NewSegTree(a []int) *SegTree {
	s := &SegTree{t: make([]int, 4*len(a)), n: len(a)}
	s.build(a, 1, 0, s.n-1)
	return s
}

// build makes the card for positions l..r.
func (s *SegTree) build(a []int, node, l, r int) {
	if l == r { // one family: copy the envelope
		s.t[node] = a[l]
		return
	}
	m := (l + r) / 2         // split in the middle
	s.build(a, 2*node, l, m) // left half first
	s.build(a, 2*node+1, m+1, r)
	s.t[node] = s.t[2*node] + s.t[2*node+1] // pool both halves
}

func main() {
	donations := []int{5, 3, 7, 2, 6, 4, 1, 8}
	tree := NewSegTree(donations)
	// root, then level by level: 36 | 17 19 | 8 9 10 9 | the eight envelopes
	fmt.Println(tree.t[1:16])
}

Time: O(n) to build · Extra space: O(n). Every circle is made exactly once, and there are only about twice as many circles as items.

Watch out for

  • Reserving only 2n slots for a size that is not a power of two. Use 4n with the 2k / 2k+1 numbering and you are safe.
  • Forgetting the base case (single item), which makes the recursion split forever.
  • Splitting with an off-by-one so that the right half starts at mid instead of mid + 1.

Quick check

  1. What does each circle in a sum segment tree hold?
    • One item of the row
    • The index of the largest item
    • The total of a stretch of neighbouring items
  2. How is a circle computed from its children?
    • It copies the left child
    • It combines the two child totals (adds them for sums)
    • It is chosen randomly
  3. How many times is each circle created during a build?
    • Twice
    • As many times as its depth
    • Once