Practice Discrete Math

Algorithms / Segment Tree Range Query

Least You Need to Know: Segment Trees, Range Queries, and Overlap Cases

Segment trees recursively partition an array into intervals so that range aggregates can be answered in `O(log n)` by combining a small number of stored interval results. The key interview idea is to reason about **no overlap**, **partial overlap**, and **complete overlap**.

The least you need to know

Key notation

[l, r] interval represented by a tree node
identity neutral value for non-overlap, such as 0 for sum
combine merge child answers into a parent answer

Tiny worked example

  • The root covers the whole array.
  • A sum query on a subrange recursively visits only nodes whose intervals overlap that subrange.
  • Fully covered nodes contribute their stored sums directly.
  • Non-overlapping nodes contribute zero, the identity for addition.

Common mistakes

How to recognize this kind of problem

Start practice