Segment Trees: Answering Range Queries Without Rescanning the Array
A practical walkthrough of segment trees — the structure that turns O(n) range queries and updates into O(log n) — and why the same idea underlies real-time analytics and time-series systems.

Muhammad Gilang Ramadhan
Software Engineer
The Problem It Solves
A segment tree answers two kinds of questions efficiently on an array: 'what is the sum/min/max/gcd of elements between index l and r?' and 'update the value at index i.' A naive approach recomputes a range answer in O(n) per query; a segment tree pushes both operations down to O(log n) by precomputing answers for fixed sub-ranges and combining them.
It's built as a binary tree over the array, where each node stores the aggregated answer for the range it represents: the root covers the whole array, leaves cover single elements, and every internal node combines its two children.
Building, Querying, and Updating
Construction is O(n): build recursively, combining children into parents. A query walks down from the root, splitting the requested range across at most O(log n) nodes whose ranges are fully or partially covered. A point update walks a single root-to-leaf path and recomputes the O(log n) ancestors on the way back up.
- Point update, range query — the classic form (sum, min, max, gcd).
- Range update, range query — needs lazy propagation to stay O(log n).
- Merge sort tree, persistent segment tree — variants for order statistics and versioned history.
Where the Same Idea Shows Up in Production
The core trick — precompute range aggregates so you never rescan raw data — is the same idea behind time-series rollups, real-time dashboards, and range-based rate limiters. Building progress tracking and queue diagnostics for Nexius AI relied on the same mental model: don't recompute a summary from scratch on every request; maintain a structure that answers 'what happened in this window' in far less than linear time.
Competitive programming is where I learned to reach for this trade-off instinctively — spend a little more on the write path so the read path stays fast, which matters far more once traffic scales.

written by
Muhammad Gilang Ramadhan
Software engineer building distributed backend systems and applied AI products, with a background in competitive programming.