AlgoViz

Segment tree

hard 24 min

A segment tree is a binary tree in which every node stores the answer (sum, min, max, GCD) for one range of an array.

Where it shows up

The same pattern appears across everyday software.

  • Competitive programming

    Problems with up to 10^5 or 10^6 mixed queries and updates on an array (range sums, range minimum, counting inversions) are the textbook use; a segment tree with lazy propagation is a standard contest template.

  • Calendar and booking systems

    To find the most overlapping bookings in a time range, store a count per time slot, apply each booking as a range add and ask for the range maximum. Interval-booking interview problems are solved exactly this way.

  • Area of overlapping rectangles

    Sweep-line algorithms in computational geometry and chip layout move a line across the plane and keep a segment tree over the y-axis that tracks how much of it is currently covered, giving the union area in O(n log n).

  • Range statistics over live data

    Dashboards that ask for the minimum, maximum or total over an arbitrary window of a series that keeps receiving corrections can keep a segment tree over the buckets, so both corrections and window queries stay logarithmic.

  • Path queries on trees

    Heavy-light decomposition cuts a tree into chains, lays each chain out in an array and puts a segment tree over it, so the maximum or sum along any path between two nodes takes O(log^2 n).