Data Structures · Visualization
Segment Tree: Introduction
Segment Tree
A segment tree is a binary tree built over an array where each node represents a range (segment) of the array, and stores a summary value for that range — most commonly a sum, but it could be a min, max, or other combinable value. Time: O(log n) for range query and point update, O(n) to build. Space: O(n).
Big-O: Build O(n); range query and point update O(log n).
Segment Tree: Introduction
Segment TreeA segment tree is a binary tree built over an array where each node represents a range (segment) of the array, and stores a summary value for that range — most commonly a sum, but it could be a min, max, or other combinable value. The root covers the whole array, and each node's two children split its range in half. This structure lets you answer 'summary of any range' queries and update individual elements much faster than recalculating from scratch each time.
How Segment Tree: Introduction Works
- The root node represents the entire array's range and stores its combined value (e.g. sum).
- Split the range in half; the left child covers the first half, the right child covers the second half.
- Keep splitting recursively until each leaf node represents a single array element.
- Every internal node's value is the combination (e.g. sum) of its two children's values.
Segment Tree: Introduction Worked Example
Input: Build a sum segment tree over [1, 3, 5, 7]
- Leaves: [1], [3], [5], [7]
- Combine pairs: [1,3] -> 4, [5,7] -> 12
- Combine the two halves: [1,3,5,7] -> 16 (the root)
Output: 16 / \ 4 12 / \ / \ 1 3 5 7
Press ▶ Run to watch it step by step.
# Segment tree: 2n array.
# leaves hold the array; parents hold the
# SUM of their children.
n = 8
tree = [1, 3, 5, 7]
# node i's children: 2*i and 2*i+1
# example: intro on [1, 3, 5, 7]Segment Tree: Introduction Time & Space Complexity
When to Use Segment Tree: Introduction
- Fast range-sum, range-min, or range-max queries over a changing array
- Competitive programming problems involving repeated range queries and updates
- Interval scheduling and range-based statistics in real-time systems
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.