AlgoTales · Roadmap

Range minimum/maximum

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

Where you will meet this in real life

A segment tree can store the smallest or largest value of each block instead of sums. Asking for the minimum or maximum over any range then combines a few stored block answers, even while single values are being changed.

Practical use cases

  • Web app: Coldest night in a weather log. A weather page stores hourly temperatures for years and lets visitors pick two dates to see the lowest temperature in that period. The tree returns it from a few blocks instead of scanning thousands of readings.
  • Web app: Peak load for any time window. An uptime monitor lets engineers highlight a window and see the maximum response time in it. Combining a few stored maximums answers it at once, even as new readings keep arriving. The graph and the "worst moment" label update together, and old readings are never rescanned.
  • System: Skyline and histogram problems. Classic problems such as the largest rectangle in a histogram, and sports statistics like best score between rounds, need quick range min or max again and again. Each of these needs the best or worst value in many different ranges, so the quick block answers save a huge amount of repeated scanning.

The story: The Station Master's Best and Worst

At the little railway station near Mira's school, the station master Mr. Qureshi keeps a notebook of how many minutes each train ran late. Eight trains run daily. Every evening the district office phones: "What was the smallest delay among trains 1 to 4?" or "What was the worst delay among trains 3 to 6?"

Mira noticed something. "A sum-tree adds the two children. But the station master does not want a total. He wants the best of a stretch. What if each circle simply keeps the smaller of its two children?" She rebuilt the tree: pairs keep the smaller of the pair, groups of four keep the smaller of the two pairs, and the root keeps the smallest delay of all. For the worst delay, she just swapped to "keep the bigger".

Mr. Qureshi tried a question for trains 1 to 4. The tree's root said 1, but Mira shouted, "Careful! That 1 belongs to train 6, which is not in your question!" So the rules stayed the same: take a circle only if it is entirely inside the question; for a circle that is outside, use a "never wins" value like infinity; for a circle that is partly inside, ask its children. The answer was found by comparing three small numbers. That is a segment tree for range minimum or maximum.

How to spot this problem, and where you need it

You need the lowest, highest, cheapest or slowest value within a chosen range repeatedly, and scanning the range every time is slow.

Signs you need it

  • The question is "what is the minimum or maximum between positions a and b?".
  • You use min() or max() over a sliced array inside a loop of requests.
  • Values can change over time, so a one-time table is not enough.
  • The same data is asked about with thousands of different ranges.

Where to use it in a project

  • Weather, sensor and server-monitoring dashboards that show extremes.
  • Price trackers and sports statistics pages that show best or worst in a period.

The solution

Build a segment tree where each node stores the minimum (or maximum) of its two children. For a range query, use blocks fully inside the range and combine them with min (or max), skipping blocks fully outside and splitting only partly overlapping ones. For an update, change the leaf and recompute its ancestors.

Payoff: Before: scanning 10,000 readings for each range. After: combining about 15 blocks.

Explain it like I am 8

In a cricket tournament, every group of teams has a "best score of this group" card. To find the best score among teams 2 to 5, you cannot use a group card if it includes teams outside 2 to 5. You use only the cards that are completely inside, and compare their best scores.

How it works, step by step

  1. Change the combine rule. Use min(left, right) for the smallest value, or max(left, right) for the largest.
  2. Pick a "never wins" value for circles that are outside the question: infinity for min, minus infinity for max.
  3. Build the same way as a sum tree: recursion, then combine children.
  4. Query with the three rules: outside returns the never-wins value, inside returns the circle's value, partly asks both children and combines them with min or max.
  5. Updates work the same: change a leaf, then recompute each ancestor with min or max on the way up.

The code in four languages

PHP

<?php
// One tree class for any "pick one of two" rule: min, max, ...
class PickTree {
    private array $t;
    private int $n;
    private $pick;          // function that combines two values
    private $never;         // value that can never win (outside circles return it)

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

    private function build(array $a, int $node, int $l, int $r): void {
        if ($l === $r) { $this->t[$node] = $a[$l]; return; }
        $m = intdiv($l + $r, 2);
        $this->build($a, 2 * $node, $l, $m);
        $this->build($a, 2 * $node + 1, $m + 1, $r);
        $this->t[$node] = ($this->pick)($this->t[2 * $node], $this->t[2 * $node + 1]);
    }

    public function query(int $ql, int $qr, int $node = 1, int $l = 0, ?int $r = null) {
        $r ??= $this->n - 1;
        if ($qr < $l || $r < $ql) return $this->never;      // outside: can never win
        if ($ql <= $l && $r <= $qr) return $this->t[$node]; // inside: take it
        $m = intdiv($l + $r, 2);                            // partly: ask both children
        return ($this->pick)($this->query($ql, $qr, 2 * $node, $l, $m),
                             $this->query($ql, $qr, 2 * $node + 1, $m + 1, $r));
    }

    public function set(int $pos, int $v, int $node = 1, int $l = 0, ?int $r = null): void {
        $r ??= $this->n - 1;
        if ($l === $r) { $this->t[$node] = $v; return; }
        $m = intdiv($l + $r, 2);
        if ($pos <= $m) $this->set($pos, $v, 2 * $node, $l, $m);
        else            $this->set($pos, $v, 2 * $node + 1, $m + 1, $r);
        $this->t[$node] = ($this->pick)($this->t[2 * $node], $this->t[2 * $node + 1]);
    }
}

$delays = [5, 3, 7, 2, 6, 4, 1, 8];
$least = new PickTree($delays, 'min', PHP_INT_MAX);
$worst = new PickTree($delays, 'max', PHP_INT_MIN);
echo $least->query(1, 4) . PHP_EOL;   // min(3,7,2,6) = 2
echo $worst->query(3, 6) . PHP_EOL;   // max(2,6,4,1) = 6
$least->set(3, 0);                    // train 3 ran on time!
echo $least->query(1, 4) . PHP_EOL;   // 0

JavaScript

// One tree class for any "pick one of two" rule: min, max, ...
class PickTree {
  constructor(a, pick, never) {
    this.n = a.length;
    this.pick = pick;                 // function that combines two values
    this.never = never;               // value that can never win (outside circles return it)
    this.t = new Array(4 * this.n).fill(never);
    this.build(a, 1, 0, this.n - 1);
  }

  build(a, node, l, r) {
    if (l === r) { this.t[node] = a[l]; return; }
    const m = (l + r) >> 1;
    this.build(a, 2 * node, l, m);
    this.build(a, 2 * node + 1, m + 1, r);
    this.t[node] = this.pick(this.t[2 * node], this.t[2 * node + 1]);
  }

  query(ql, qr, node = 1, l = 0, r = this.n - 1) {
    if (qr < l || r < ql) return this.never;       // outside: can never win
    if (ql <= l && r <= qr) return this.t[node];   // inside: take it
    const m = (l + r) >> 1;                        // partly: ask both children
    return this.pick(this.query(ql, qr, 2 * node, l, m),
                     this.query(ql, qr, 2 * node + 1, m + 1, r));
  }

  set(pos, v, node = 1, l = 0, r = this.n - 1) {
    if (l === r) { this.t[node] = v; return; }
    const m = (l + r) >> 1;
    if (pos <= m) this.set(pos, v, 2 * node, l, m);
    else          this.set(pos, v, 2 * node + 1, m + 1, r);
    this.t[node] = this.pick(this.t[2 * node], this.t[2 * node + 1]);
  }
}

const delays = [5, 3, 7, 2, 6, 4, 1, 8];
const least = new PickTree(delays, Math.min, Infinity);
const worst = new PickTree(delays, Math.max, -Infinity);
console.log(least.query(1, 4));   // min(3,7,2,6) = 2
console.log(worst.query(3, 6));   // max(2,6,4,1) = 6
least.set(3, 0);                  // train 3 ran on time!
console.log(least.query(1, 4));   // 0

Java

import java.util.*;
import java.util.function.IntBinaryOperator;

public class Main {
    // One tree class for any "pick one of two" rule: min, max, ...
    static class PickTree {
        int[] t;
        int n;
        IntBinaryOperator pick;     // function that combines two values
        int never;                  // value that can never win (outside circles return it)

        PickTree(int[] a, IntBinaryOperator pick, int never) {
            this.n = a.length;
            this.pick = pick;
            this.never = never;
            this.t = new int[4 * n];
            Arrays.fill(t, never);
            build(a, 1, 0, n - 1);
        }

        void build(int[] a, int node, int l, int r) {
            if (l == r) { t[node] = a[l]; return; }
            int m = (l + r) / 2;
            build(a, 2 * node, l, m);
            build(a, 2 * node + 1, m + 1, r);
            t[node] = pick.applyAsInt(t[2 * node], t[2 * node + 1]);
        }

        int query(int ql, int qr) { return query(ql, qr, 1, 0, n - 1); }

        int query(int ql, int qr, int node, int l, int r) {
            if (qr < l || r < ql) return never;             // outside: can never win
            if (ql <= l && r <= qr) return t[node];         // inside: take it
            int m = (l + r) / 2;                            // partly: ask both children
            return pick.applyAsInt(query(ql, qr, 2 * node, l, m),
                                   query(ql, qr, 2 * node + 1, m + 1, r));
        }

        void set(int pos, int v) { set(pos, v, 1, 0, n - 1); }

        void set(int pos, int v, int node, int l, int r) {
            if (l == r) { t[node] = v; return; }
            int m = (l + r) / 2;
            if (pos <= m) set(pos, v, 2 * node, l, m);
            else          set(pos, v, 2 * node + 1, m + 1, r);
            t[node] = pick.applyAsInt(t[2 * node], t[2 * node + 1]);
        }
    }

    public static void main(String[] args) {
        int[] delays = {5, 3, 7, 2, 6, 4, 1, 8};
        PickTree least = new PickTree(delays, Math::min, Integer.MAX_VALUE);
        PickTree worst = new PickTree(delays, Math::max, Integer.MIN_VALUE);
        System.out.println(least.query(1, 4));  // min(3,7,2,6) = 2
        System.out.println(worst.query(3, 6));  // max(2,6,4,1) = 6
        least.set(3, 0);                        // train 3 ran on time!
        System.out.println(least.query(1, 4));  // 0
    }
}

Go

package main

import (
	"fmt"
	"math"
)

// PickTree is one tree for any "pick one of two" rule: min, max, ...
type PickTree struct {
	t     []int
	n     int
	pick  func(a, b int) int // function that combines two values
	never int                // value that can never win (outside circles return it)
}

func NewPickTree(a []int, pick func(a, b int) int, never int) *PickTree {
	p := &PickTree{t: make([]int, 4*len(a)), n: len(a), pick: pick, never: never}
	for i := range p.t {
		p.t[i] = never
	}
	p.build(a, 1, 0, p.n-1)
	return p
}

func (p *PickTree) build(a []int, node, l, r int) {
	if l == r {
		p.t[node] = a[l]
		return
	}
	m := (l + r) / 2
	p.build(a, 2*node, l, m)
	p.build(a, 2*node+1, m+1, r)
	p.t[node] = p.pick(p.t[2*node], p.t[2*node+1])
}

func (p *PickTree) Query(ql, qr int) int { return p.query(ql, qr, 1, 0, p.n-1) }

func (p *PickTree) query(ql, qr, node, l, r int) int {
	if qr < l || r < ql { // outside: can never win
		return p.never
	}
	if ql <= l && r <= qr { // inside: take it
		return p.t[node]
	}
	m := (l + r) / 2 // partly: ask both children
	return p.pick(p.query(ql, qr, 2*node, l, m),
		p.query(ql, qr, 2*node+1, m+1, r))
}

func (p *PickTree) Set(pos, v int) { p.set(pos, v, 1, 0, p.n-1) }

func (p *PickTree) set(pos, v, node, l, r int) {
	if l == r {
		p.t[node] = v
		return
	}
	m := (l + r) / 2
	if pos <= m {
		p.set(pos, v, 2*node, l, m)
	} else {
		p.set(pos, v, 2*node+1, m+1, r)
	}
	p.t[node] = p.pick(p.t[2*node], p.t[2*node+1])
}

func minOf(a, b int) int {
	if a < b {
		return a
	}
	return b
}

func maxOf(a, b int) int {
	if a > b {
		return a
	}
	return b
}

func main() {
	delays := []int{5, 3, 7, 2, 6, 4, 1, 8}
	least := NewPickTree(delays, minOf, math.MaxInt)
	worst := NewPickTree(delays, maxOf, math.MinInt)
	fmt.Println(least.Query(1, 4)) // min(3,7,2,6) = 2
	fmt.Println(worst.Query(3, 6)) // max(2,6,4,1) = 6
	least.Set(3, 0)                // train 3 ran on time!
	fmt.Println(least.Query(1, 4)) // 0
}

Time: Build O(n), query and update O(log n) · Extra space: O(n). Same shape as the sum tree; only the "combine" rule and the "never wins" value change.

Watch out for

  • Returning 0 for "outside" in a minimum tree. A 0 would win the contest and ruin the answer. Use infinity.
  • Trusting a circle that is only partly inside because its value looks small. Only fully-inside circles can be taken whole.
  • Trying to answer a minimum with prefix-minimum subtraction. You cannot "undo" a minimum, so the tree (or a sparse table) is needed.

Quick check

  1. For a range-minimum tree, what should an outside circle return?
    • 0
    • Its own minimum
    • Infinity (a value that never wins)
  2. What does each circle store?
    • The sum of its stretch
    • The smallest value of its stretch
    • The position of its stretch's first item
  3. How do you change the tree to answer maximum instead?
    • Add a second root
    • Sort the data first
    • Rebuild with max and use minus infinity as the never-wins value