Segment Trees: The Matrix of Range Queries
The Quest Begins (The "Why") I still remember the first time I faced a problem that asked for the sum of numbers in a sub‑array, over and over again, with updates sprinkled in between. It felt like I was stuck in a never‑ending loop of for i in range(l, r+1): total += arr[i] – O(n) per query, and with up to 10⁵ queries the solution timed out every single time. I was staring at the screen, thinking, “There has to be a smarter way to answer these range questions without scanning the whole array each time.” That moment was my dragon: a seemingly simple problem that kept biting me because I kept reaching for the brute‑force sword. I needed a data structure that could give me the answer in logarithmic time while still supporting point updates. Enter the segment tree – the tool that turned my O(n·q) nightmare into an O((n+q)·log n) victory. The Revelation (The Insight) So why does a segment tree work? Imagine you have an array and you want to know the sum of any interval [l, r] . If you could break that interval into a handful of pre‑computed chunks, you’d only need to add those chunk values together instead of touching every element. A segment tree is exactly that: a binary tree where each node stores the aggregate (sum, min, max, etc.) of a segment of the original array. The root covers the whole array [0, n‑1] . Its two children cover the left half and the right half, and this keeps splitting until the leaves represent single elements. The magic lies in two facts: Every node’s value is a function of its children. If you know the sum of the left child and the sum of the right child, the parent’s sum is just their addition. This means we can build the tree bottom‑up in O(n) time. Any interval can be represented as O(log n) disjoint nodes. When you walk down the tree to answer [l, r] , you either take a whole node (if its segment lies completely inside the query) or you recurse further. Because the tree’s height is log₂n, you’ll visit at most 2·log₂n nodes. Thus, building