Segment Tree
A tree for quickly computing range sums, minimums, and the like. Each node owns one interval, handling both point updates and range queries in O(log n) — covering the update weakness of a prefix-sum array.
01Segment Tree
Explore How It WorksSegment tree. Over the array [1, 3, 5, 7], each node holds the sum of its own interval.
Leaves are the elements themselves, and each parent is the sum of its two children. Merging upward, the root becomes the total sum 16.
query(1, 3) · compute the sum of indices 1 to 3. Start descending from the root [0,3].
The left [0,1] only partially overlaps the query. Descend further and adopt just [1,1]=3.
The right [2,3] is fully contained in the query. Adopt all of 12 without descending further.
Combine the adopted pieces · 3 + 12 = 15. We got the range sum in O(log n) without adding up every leaf.
02 Understand It Simply
For EveryoneHalves the range recursively and stores each range's sum at its node, answering range sums and point updates both in O(log n).
A tree where each node holds the sum (or minimum) of a certain interval.
Whether one value changes or you ask for a wide range's sum, it answers in O(log n).
- –Range sum/minimum queries
- –live rankings and stats
- –game scoreboards
03 Python Implementation
A clean, readable reference implementation of the core logic of Segment Tree.
04 Frequently Asked Questions
FAQWhat is Segment Tree?+
A tree for quickly computing range sums, minimums, and the like. Each node owns one interval, handling both point updates and range queries in O(log n) — covering the update weakness of a prefix-sum array.
What is the time complexity of Segment Tree?+
The time complexity of Segment Tree is Query/Update O(log n). Follow the step-by-step visualization to see exactly why.
Where is Segment Tree used?+
Range sum/minimum queries, live rankings and stats, game scoreboards.
What's a simple analogy for Segment Tree?+
Halves the range recursively and stores each range's sum at its node, answering range sums and point updates both in O(log n).
