Segment Trees
A Segment Tree is a tree-based data structure used to answer range queries efficiently. A range query means finding information about a particular section of an array, such as the sum, minimum, or maximum value between two indexes. Segment Trees are especially useful when an array contains many queries and updates.
1. What Is a Segment Tree?
A Segment Tree is a binary tree in which every node represents a segment, or range, of an array.
Each node stores some information about its range. For example, it may store the sum of all elements in that range, the minimum element, or the maximum element.
The root represents the entire array. Its children represent smaller parts of the array. This division continues until each leaf represents a single array element.
2. Why Do We Need a Segment Tree?
Imagine that we have an array:
arr = [2, 4, 6, 8, 10, 12]
Suppose we want to find the sum of elements from index 1 to index 4.
The required elements are:
4 + 6 + 8 + 10 = 28
We can calculate this sum by visiting every element in the requested range. This is called a range query.
However, imagine that we have thousands of queries and also need to update array elements frequently. Recalculating every range from scratch can become inefficient.
A Segment Tree stores information about different ranges in advance. This allows us to answer many queries without checking every element in the range.
3. Understanding Range Queries
A range query asks us to calculate something for elements between two indexes.
Common range queries include:
- Find the sum of elements between indexes L and R.
- Find the minimum element between indexes L and R.
- Find the maximum element between indexes L and R.
- Find the greatest common divisor of elements in a range.
- Find the product of elements in a range.
Example
Consider the array:
arr = [5, 3, 8, 6, 2, 7]
Suppose the query is:
Find the sum from index 1 to index 4
The selected elements are:
3, 8, 6, 2
Therefore:
3 + 8 + 6 + 2 = 19
Answer = 19
4. Structure of a Segment Tree
A Segment Tree is a binary tree. Every node represents a range of array indexes.
Let's understand this using the following array:
arr = [2, 4, 6, 8]
The root represents the complete range from index 0 to index 3. It is divided into two smaller ranges:
- Left child represents indexes 0 to 1.
- Right child represents indexes 2 to 3.
Each of these ranges is divided again until we reach individual array elements.
[0,3]
/ \
[0,1] [2,3]
/ \ / \
[0,0][1,1] [2,2][3,3]
Array: 2 4 6 8
If we build a sum Segment Tree, each node stores the sum of its represented range.
20
/ \
6 14
/ \ / \
2 4 6 8
Here:
- Node [0,3] stores 2 + 4 + 6 + 8 = 20.
- Node [0,1] stores 2 + 4 = 6.
- Node [2,3] stores 6 + 8 = 14.
- Leaf nodes store individual array values.
5. How Is a Segment Tree Stored?
Although a Segment Tree is logically a binary tree, we usually implement it using an array.
We use a separate array called tree
to store the nodes of the Segment Tree.
If a node is stored at index i, its children are stored at:
- Left child: 2 × i
- Right child: 2 × i + 1
This formula is used when we store the root at index 1.
Example
If a parent node is at index 1:
- Left child is at index 2.
- Right child is at index 3.
If a parent node is at index 2:
- Left child is at index 4.
- Right child is at index 5.
For an array containing N elements, we commonly allocate approximately
4 * N positions for the Segment Tree.
This provides enough space for the recursive tree structure.
6. Main Operations of a Segment Tree
A basic Segment Tree supports three important operations:
1. Build
Building means creating the Segment Tree from the original array. We divide the array into smaller ranges and calculate the value stored at every node.
2. Query
A query calculates information for a requested range. For example, it can find the sum of elements from index L to R.
3. Update
An update changes an array element and updates the corresponding Segment Tree nodes so that future queries return correct answers.
| Operation | Purpose |
|---|---|
| Build | Create the tree from the array. |
| Query | Calculate information for a range. |
| Update | Change an element and update the tree. |
7. Building a Sum Segment Tree
Let's build a Segment Tree that stores the sum of elements.
Consider this array:
arr = [2, 4, 6, 8]
We start with the complete range from index 0 to index 3.
Step 1: Calculate the Root
The root represents indexes 0 to 3.
2 + 4 + 6 + 8 = 20
Step 2: Divide the Range
The middle index is:
mid = (0 + 3) / 2 = 1
Now divide the range:
- Left range: 0 to 1
- Right range: 2 to 3
Step 3: Calculate the Left Child
arr[0] + arr[1]
= 2 + 4
= 6
Step 4: Calculate the Right Child
arr[2] + arr[3]
= 6 + 8
= 14
Step 5: Divide Until Single Elements
Continue dividing each range until every range contains only one element.
20
/ \
6 14
/ \ / \
2 4 6 8
8. C++ Code to Build a Sum Segment Tree
We use a recursive function to build the tree. Recursion helps us divide each range into smaller ranges.
#include <iostream>
#include <vector>
using namespace std;
void build(
int node,
int start,
int end,
vector<int>& arr,
vector<int>& tree
) {
// Base case: only one element
if (start == end) {
tree[node] = arr[start];
return;
}
int mid = start + (end - start) / 2;
// Build left child
build(
2 * node,
start,
mid,
arr,
tree
);
// Build right child
build(
2 * node + 1,
mid + 1,
end,
arr,
tree
);
// Combine child results
tree[node] =
tree[2 * node] + tree[2 * node + 1];
}
Understanding the Parameters
-
node: Current position in the Segment Tree array. -
start: Starting index of the current array range. -
end: Ending index of the current array range. -
arr: Original array. -
tree: Array used to store Segment Tree nodes.
Understanding the Base Case
if (start == end) {
tree[node] = arr[start];
return;
}
When start and end are equal, the range contains only one element. We store that element in the current tree node.
Understanding the Recursive Calls
build(2 * node, start, mid, arr, tree);
build(2 * node + 1, mid + 1, end, arr, tree);
The first call builds the left half of the range. The second call builds the right half.
Combining the Results
tree[node] =
tree[2 * node] + tree[2 * node + 1];
After both children are built, we add their values and store the result in the parent node.
9. Range Sum Query
Once the Segment Tree is built, we can use it to find the sum of elements in a requested range.
Suppose we have:
arr = [2, 4, 6, 8]
We want to find the sum from index 1 to index 3.
4 + 6 + 8 = 18
During a query, every Segment Tree node's range can fall into one of three categories.
Case 1: No Overlap
The current node's range does not contain any requested index. We do not need this node, so we return 0 for a sum query.
Case 2: Complete Overlap
The current node's entire range is inside the requested range. We can directly return the value stored at this node.
Case 3: Partial Overlap
The current node's range overlaps the requested range only partially. We search both children and combine their results.
- No overlap: Ignore the node.
- Complete overlap: Use the stored answer.
- Partial overlap: Search the children.
10. C++ Code for Range Sum Query
int query(
int node,
int start,
int end,
int left,
int right,
vector<int>& tree
) {
// No overlap
if (right < start || end < left) {
return 0;
}
// Complete overlap
if (left <= start && end <= right) {
return tree[node];
}
// Partial overlap
int mid = start + (end - start) / 2;
int leftSum = query(
2 * node,
start,
mid,
left,
right,
tree
);
int rightSum = query(
2 * node + 1,
mid + 1,
end,
left,
right,
tree
);
return leftSum + rightSum;
}
Explanation of the Query Function
1. No Overlap:
if (right < start || end < left) {
return 0;
}
If the current range is completely outside the requested range, it contributes nothing to the sum.
2. Complete Overlap:
if (left <= start && end <= right) {
return tree[node];
}
If the current node represents a range fully included in the requested range, we can return its stored sum immediately.
3. Partial Overlap:
int leftSum = query(...);
int rightSum = query(...);
return leftSum + rightSum;
We search both children and add their answers.
11. Dry Run of Range Sum Query
Consider:
arr = [2, 4, 6, 8]
Our query is:
query(1, 3)
We want the sum of indexes 1 through 3.
| Range | Stored Sum | Query Condition | Action |
|---|---|---|---|
| [0,3] | 20 | Partial overlap | Search both children |
| [0,1] | 6 | Partial overlap | Search children |
| [0,0] | 2 | No overlap | Return 0 |
| [1,1] | 4 | Complete overlap | Return 4 |
| [2,3] | 14 | Complete overlap | Return 14 |
Now combine the results:
0 + 4 + 14 = 18
18
12. Updating an Element in a Segment Tree
A Segment Tree can also update an array element efficiently.
Suppose our original array is:
arr = [2, 4, 6, 8]
Now we want to change the element at index 2 from 6 to 10.
The updated array becomes:
arr = [2, 4, 10, 8]
We must update the corresponding leaf node and all its ancestors.
The updated Segment Tree will be:
24
/ \
6 18
/ \ / \
2 4 10 8
Notice that only the nodes on the path from the updated leaf to the root need to be recalculated.
13. C++ Code for Updating an Element
void update(
int node,
int start,
int end,
int index,
int value,
vector<int>& tree
) {
// Found the required leaf
if (start == end) {
tree[node] = value;
return;
}
int mid = start + (end - start) / 2;
if (index <= mid) {
update(
2 * node,
start,
mid,
index,
value,
tree
);
} else {
update(
2 * node + 1,
mid + 1,
end,
index,
value,
tree
);
}
// Recalculate the parent
tree[node] =
tree[2 * node] + tree[2 * node + 1];
}
Understanding the Update Function
First, we check whether the current range represents a single element. If it does, we update that leaf node.
if (start == end) {
tree[node] = value;
return;
}
Otherwise, we calculate the middle index and decide which child contains the required index.
- If the index is less than or equal to mid, go left.
- Otherwise, go right.
After updating the child, we recalculate the parent by adding its two child values.
14. Complete C++ Program: Build, Query, and Update
Now let's combine all three operations into one complete program.
#include <iostream>
#include <vector>
using namespace std;
void build(
int node,
int start,
int end,
vector<int>& arr,
vector<int>& tree
) {
if (start == end) {
tree[node] = arr[start];
return;
}
int mid = start + (end - start) / 2;
build(2 * node, start, mid, arr, tree);
build(2 * node + 1, mid + 1, end, arr, tree);
tree[node] =
tree[2 * node] + tree[2 * node + 1];
}
int query(
int node,
int start,
int end,
int left,
int right,
vector<int>& tree
) {
if (right < start || end < left) {
return 0;
}
if (left <= start && end <= right) {
return tree[node];
}
int mid = start + (end - start) / 2;
int leftSum = query(
2 * node,
start,
mid,
left,
right,
tree
);
int rightSum = query(
2 * node + 1,
mid + 1,
end,
left,
right,
tree
);
return leftSum + rightSum;
}
void update(
int node,
int start,
int end,
int index,
int value,
vector<int>& tree
) {
if (start == end) {
tree[node] = value;
return;
}
int mid = start + (end - start) / 2;
if (index <= mid) {
update(
2 * node,
start,
mid,
index,
value,
tree
);
} else {
update(
2 * node + 1,
mid + 1,
end,
index,
value,
tree
);
}
tree[node] =
tree[2 * node] + tree[2 * node + 1];
}
int main() {
vector<int> arr = {2, 4, 6, 8};
int n = arr.size();
vector<int> tree(4 * n, 0);
// Build the Segment Tree
build(1, 0, n - 1, arr, tree);
// Query sum from index 1 to 3
cout << "Initial sum: "
<< query(1, 0, n - 1, 1, 3, tree)
<< endl;
// Update index 2 to 10
update(1, 0, n - 1, 2, 10, tree);
// Query again after update
cout << "Updated sum: "
<< query(1, 0, n - 1, 1, 3, tree)
<< endl;
return 0;
}
15. Dry Run of the Complete Program
Original array:
[2, 4, 6, 8]
Step 1: Build the Segment Tree
The tree stores the sums of different ranges. The root stores 20.
Step 2: Perform the First Query
We calculate the sum from index 1 to index 3.
4 + 6 + 8 = 18
Step 3: Update Index 2
We change the value at index 2 from 6 to 10.
[2, 4, 10, 8]
Step 4: Perform the Query Again
Now the sum from index 1 to index 3 is:
4 + 10 + 8 = 22
Initial sum: 18
Updated sum: 22
16. Time Complexity of Segment Tree
A Segment Tree divides the array into smaller ranges. Its height is approximately log₂(N), where N is the number of array elements.
| Operation | Time Complexity | Explanation |
|---|---|---|
| Build | O(N) | Every tree node is built once. |
| Range Query | O(log N) | Only a limited number of tree nodes are visited at each level. |
| Point Update | O(log N) | Only one root-to-leaf path is updated. |
Space Complexity
A Segment Tree is commonly stored in an array of size approximately 4 × N.
Therefore, its space complexity is:
O(N)
17. Segment Tree vs Normal Array
Let's compare a normal array with a Segment Tree when we need range queries and updates.
| Operation | Normal Array | Segment Tree |
|---|---|---|
| Build | Already available | O(N) |
| Range Sum Query | O(N) in the worst case | O(log N) |
| Point Update | O(1) | O(log N) |
| Extra Memory | Very little | O(N) |
A normal array is simpler and may be better when we rarely perform range queries. A Segment Tree is useful when we need many range queries and updates.
18. Different Types of Segment Trees
Segment Trees are not limited to calculating sums. The same general structure can store different types of information.
1. Sum Segment Tree
Stores the sum of elements in each range.
2. Minimum Segment Tree
Stores the smallest element in each range.
3. Maximum Segment Tree
Stores the largest element in each range.
4. GCD Segment Tree
Stores the greatest common divisor of elements in each range.
5. Lazy Propagation Segment Tree
This is an advanced version used when we need to update an entire range efficiently instead of updating elements one by one.
19. Advantages of Segment Trees
- Range queries can be answered efficiently.
- Point updates can be performed efficiently.
- They support many operations such as sum, minimum, and maximum.
- They are useful when queries and updates are performed repeatedly.
- They can be extended to handle range updates using lazy propagation.
20. Disadvantages of Segment Trees
- They require additional memory.
- Implementation is more complicated than a normal array.
- Recursive functions can be difficult for beginners to understand.
- For small arrays or very few queries, a simple array may be easier.
21. Common Mistakes While Implementing Segment Trees
- Incorrect range boundaries: Always be careful about the start and end indexes of each node.
- Wrong child indexes: If the root is stored at index 1, use 2 × node for the left child and 2 × node + 1 for the right child.
- Incorrect no-overlap return value: For a sum query, return 0. Other query types require their own suitable neutral value.
- Forgetting to update parent nodes: After changing a leaf, recalculate every ancestor on the path back to the root.
- Incorrect complete-overlap condition: Check that the entire current node range lies inside the requested query range.
- Allocating too little space: Using a vector of size 4 × N is a common safe choice for a recursively built Segment Tree.
22. Interview Questions
Q1. What is a Segment Tree?
A Segment Tree is a binary tree-based data structure used to answer range queries and perform updates efficiently.
Q2. What information does a Segment Tree node store?
It stores information about a particular range, such as the sum, minimum, maximum, or GCD of the elements in that range.
Q3. What is the time complexity of building a Segment Tree?
Building a basic Segment Tree takes O(N) time because every node is calculated once.
Q4. What is the time complexity of a range query?
A standard Segment Tree range query takes O(log N) time.
Q5. What is the time complexity of a point update?
A point update takes O(log N) time because only one path from the root to a leaf needs to be updated.
Q6. Why do we allocate approximately 4 × N positions?
A recursively divided Segment Tree may not be a perfectly full binary tree. Allocating approximately 4 × N positions provides enough space for its nodes.
Q7. What are the three overlap cases in a range query?
No overlap, complete overlap, and partial overlap.
Q8. What is lazy propagation?
Lazy propagation is an advanced technique that delays applying updates to individual nodes until they are needed. It helps perform range updates efficiently.
23. Practice Problems
- Build a Sum Segment Tree for the array [1, 3, 5, 7].
- Find the sum of elements from index 1 to index 3.
- Update the element at index 2 from 5 to 10.
- Find the sum again after the update.
- Implement a Segment Tree that finds the minimum element in a range.
- Implement a Segment Tree that finds the maximum element in a range.
- Explain the difference between a normal array and a Segment Tree.
24. Summary
A Segment Tree is a powerful data structure used to answer range queries and perform updates efficiently.
Important points to remember:
- A Segment Tree is a binary tree that represents ranges of an array.
- The root represents the complete array.
- Leaf nodes represent individual array elements.
- Build operation takes O(N) time.
- Range queries take O(log N) time.
- Point updates take O(log N) time.
- The usual space complexity is O(N).
- Segment Trees can store sums, minimums, maximums, and other range information.