
- DSA - Home
- DSA - Overview
- DSA - Environment Setup
- DSA - Algorithms Basics
- DSA - Asymptotic Analysis
- Data Structures
- DSA - Data Structure Basics
- DSA - Data Structures and Types
- DSA - Array Data Structure
- DSA - Skip List Data Structure
- Linked Lists
- DSA - Linked List Data Structure
- DSA - Doubly Linked List Data Structure
- DSA - Circular Linked List Data Structure
- Stack & Queue
- DSA - Stack Data Structure
- DSA - Expression Parsing
- DSA - Queue Data Structure
- DSA - Circular Queue Data Structure
- DSA - Priority Queue Data Structure
- DSA - Deque Data Structure
- Searching Algorithms
- DSA - Searching Algorithms
- DSA - Linear Search Algorithm
- DSA - Binary Search Algorithm
- DSA - Interpolation Search
- DSA - Jump Search Algorithm
- DSA - Exponential Search
- DSA - Fibonacci Search
- DSA - Sublist Search
- DSA - Hash Table
- Sorting Algorithms
- DSA - Sorting Algorithms
- DSA - Bubble Sort Algorithm
- DSA - Insertion Sort Algorithm
- DSA - Selection Sort Algorithm
- DSA - Merge Sort Algorithm
- DSA - Shell Sort Algorithm
- DSA - Heap Sort Algorithm
- DSA - Bucket Sort Algorithm
- DSA - Counting Sort Algorithm
- DSA - Radix Sort Algorithm
- DSA - Quick Sort Algorithm
- Matrices Data Structure
- DSA - Matrices Data Structure
- DSA - Lup Decomposition In Matrices
- DSA - Lu Decomposition In Matrices
- Graph Data Structure
- DSA - Graph Data Structure
- DSA - Depth First Traversal
- DSA - Breadth First Traversal
- DSA - Spanning Tree
- DSA - Topological Sorting
- DSA - Strongly Connected Components
- DSA - Biconnected Components
- DSA - Augmenting Path
- DSA - Network Flow Problems
- DSA - Flow Networks In Data Structures
- DSA - Edmonds Blossom Algorithm
- DSA - Maxflow Mincut Theorem
- Tree Data Structure
- DSA - Tree Data Structure
- DSA - Tree Traversal
- DSA - Binary Search Tree
- DSA - AVL Tree
- DSA - Red Black Trees
- DSA - B Trees
- DSA - B+ Trees
- DSA - Splay Trees
- DSA - Range Queries
- DSA - Segment Trees
- DSA - Fenwick Tree
- DSA - Fusion Tree
- DSA - Hashed Array Tree
- DSA - K-Ary Tree
- DSA - Kd Trees
- DSA - Priority Search Tree Data Structure
- Recursion
- DSA - Recursion Algorithms
- DSA - Tower of Hanoi Using Recursion
- DSA - Fibonacci Series Using Recursion
- Divide and Conquer
- DSA - Divide and Conquer
- DSA - Max-Min Problem
- DSA - Strassen's Matrix Multiplication
- DSA - Karatsuba Algorithm
- Greedy Algorithms
- DSA - Greedy Algorithms
- DSA - Travelling Salesman Problem (Greedy Approach)
- DSA - Prim's Minimal Spanning Tree
- DSA - Kruskal's Minimal Spanning Tree
- DSA - Dijkstra's Shortest Path Algorithm
- DSA - Map Colouring Algorithm
- DSA - Fractional Knapsack Problem
- DSA - Job Sequencing with Deadline
- DSA - Optimal Merge Pattern Algorithm
- Dynamic Programming
- DSA - Dynamic Programming
- DSA - Matrix Chain Multiplication
- DSA - Floyd Warshall Algorithm
- DSA - 0-1 Knapsack Problem
- DSA - Longest Common Sub-sequence Algorithm
- DSA - Travelling Salesman Problem (Dynamic Approach)
- Hashing
- DSA - Hashing Data Structure
- DSA - Collision In Hashing
- Disjoint Set
- DSA - Disjoint Set
- DSA - Path Compression And Union By Rank
- Heap
- DSA - Heap Data Structure
- DSA - Binary Heap
- DSA - Binomial Heap
- DSA - Fibonacci Heap
- Tries Data Structure
- DSA - Tries
- DSA - Standard Tries
- DSA - Compressed Tries
- DSA - Suffix Tries
- Treaps
- DSA - Treaps Data Structure
- Bit Mask
- DSA - Bit Mask In Data Structures
- Bloom Filter
- DSA - Bloom Filter Data Structure
- Approximation Algorithms
- DSA - Approximation Algorithms
- DSA - Vertex Cover Algorithm
- DSA - Set Cover Problem
- DSA - Travelling Salesman Problem (Approximation Approach)
- Randomized Algorithms
- DSA - Randomized Algorithms
- DSA - Randomized Quick Sort Algorithm
- DSA - Karger’s Minimum Cut Algorithm
- DSA - Fisher-Yates Shuffle Algorithm
- Miscellaneous
- DSA - Infix to Postfix
- DSA - Bellmon Ford Shortest Path
- DSA - Maximum Bipartite Matching
- DSA Useful Resources
- DSA - Questions and Answers
- DSA - Selection Sort Interview Questions
- DSA - Merge Sort Interview Questions
- DSA - Insertion Sort Interview Questions
- DSA - Heap Sort Interview Questions
- DSA - Bubble Sort Interview Questions
- DSA - Bucket Sort Interview Questions
- DSA - Radix Sort Interview Questions
- DSA - Cycle Sort Interview Questions
- DSA - Quick Guide
- DSA - Useful Resources
- DSA - Discussion
Segment Trees
What is Segment Tree?
Segment tree is a binary tree where each node represents an interval. The root node represents the whole array and the leaf nodes represent the single element of the array.
Segment tree is a data structure which is used for solving range queries in logarithmic time. It is used for storage of Interval or Segment of elements.
Interval
Interval is a range of elements between the start and end index.Intervals are dynamic as they change during operations. For example, if we have an array of 10 elements [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]. Then the interval between the 3rd and 7th index is [3, 4, 5, 6, 7].
Segment
The Segment is little different from the interval. Means, it is refered to a specific range that represented by the node of the segment tree. The segment is static as it does not change during operations it is fixed.
Let's understand the segment with an example.
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] // entire array [1, 2, 3, 4, 5] // segment 1 [6, 7, 8, 9, 10] // segment 2
Here, the entire array is divided into two segments. The first segment is [1, 2, 3, 4, 5] and the second segment is [6, 7, 8, 9, 10].
Usage of Segment Tree with Example
Segment tree is a data structure that is build for solving the range query problems.
For example, you have an array of 10 elements [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]. Now you have to find the minimum value between the 3rd and 7th index.
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 3rd index = 3 4th index = 4 5th index = 5 6th index = 6 7th index = 7 Minimum = 3
So, the minimum will be 3 between the 3rd and 7th index.
If we solve this problem using the general brute force approch time complexity will be O(n) where n is the total elements of the array. This is not better way to do this problem because if we have a large dataset then it will take more time to find the minimum value.
So, to solve this problem efficiently we can use the segment tree data structure. In this tutorial let's understand how we can solve this problem using the segment tree.
Note : You should be familiar with the recursion and tree data structure before learning the segment tree.
Representation of Segment Tree
Here, we will represent the segment tree using the array. The segment tree is a binary tree where each node represents an interval. The root node represents the whole array and the leaf nodes represent the single element of the array.
In the above image, the segment tree is formed for finding the maximum value in the array [3,2,1,0,4,5] where the segment of the root node is [0,5]. The left child of the root node represents the segment [0,2] and the right child of the root node represents the segment [3,5]. Similary it goes on.
Each node of the segment tree contains the following information:
- Start index of the segment
- End index of the segment
- Maximum value of the segment
- Left child of the segment
- Right child of the segment
How Segment Tree Works?
Segment tree works in the following way:
- Build the segment tree from the given array.
- Perform the range query on the segment tree.
- Update the value of the array and segment tree.
Build the Segment Tree
The sengment tree uses the recursive approach to build the tree. The steps to build the segment tree are:
- Start with the root node that represents the whole array.
- Divide the array into two equal parts and build the left and right child of the root node.
- Continue this process until the leaf node is reached.
Let's understand the steps to build the segment tree with an example.
Example
Now, we will build the segment tree for the sum query of the array [4, 3, 2, 1, 6, 7].
#include <stdio.h> #include <stdlib.h> #include <math.h> int nextPowerOf2(int n) { int power = 1; while (power < n) { power *= 2; } return power; } void buildSegmentTree(int *arr, int *segment, int low, int high, int pos) { if (low == high) { segment[pos] = arr[low]; return; } int mid = (low + high) / 2; buildSegmentTree(arr, segment, low, mid, 2 * pos + 1); buildSegmentTree(arr, segment, mid + 1, high, 2 * pos + 2); segment[pos] = segment[2 * pos + 1] + segment[2 * pos + 2]; } void printSegmentTree(int *segment, int size) { for (int i = 0; i < size; i++) { printf("%d ", segment[i]); } printf("\n"); } int main() { int arr[] = {4, 3, 2, 1, 6, 7}; int n = sizeof(arr) / sizeof(arr[0]); int segSize = 2 * nextPowerOf2(n) - 1; int *segment = (int *)malloc(segSize * sizeof(int)); for (int i = 0; i < segSize; i++) { segment[i] = 0; } buildSegmentTree(arr, segment, 0, n - 1, 0); printSegmentTree(segment, segSize); free(segment); return 0; }
Output
The output obtained is as follows −
23 9 14 4 5 6 7 4 3 2 1 0 0 0
#include <iostream> #include <vector> #include <cmath> using namespace std; int nextPowerOf2(int n) { int power = 1; while (power < n) { power *= 2; } return power; } void buildSegmentTree(vector<int> &arr, vector<int> &segment, int low, int high, int pos) { if (low == high) { segment[pos] = arr[low]; return; } int mid = (low + high) / 2; buildSegmentTree(arr, segment, low, mid, 2 * pos + 1); buildSegmentTree(arr, segment, mid + 1, high, 2 * pos + 2); segment[pos] = segment[2 * pos + 1] + segment[2 * pos + 2]; } void printSegmentTree(vector<int> &segment) { for (int i = 0; i < segment.size(); i++) { cout << segment[i] << " "; } cout << endl; } int main() { vector<int> arr = {4, 3, 2, 1, 6, 7}; int n = arr.size(); int segSize = 2 * nextPowerOf2(n) - 1; vector<int> segment(segSize, 0); buildSegmentTree(arr, segment, 0, n - 1, 0); printSegmentTree(segment); return 0; }
Output
The output produced is as follows −
23 9 14 4 5 6 7 4 3 2 1 0 0 0
import java.util.Arrays; public class SegmentTree { public static int nextPowerOf2(int n) { int power = 1; while (power < n) { power *= 2; } return power; } public static void buildSegmentTree(int[] arr, int[] segment, int low, int high, int pos) { if (low == high) { segment[pos] = arr[low]; return; } int mid = (low + high) / 2; buildSegmentTree(arr, segment, low, mid, 2 * pos + 1); buildSegmentTree(arr, segment, mid + 1, high, 2 * pos + 2); segment[pos] = segment[2 * pos + 1] + segment[2 * pos + 2]; } public static void printSegmentTree(int[] segment) { for (int i = 0; i < segment.length; i++) { System.out.print(segment[i] + " "); } System.out.println(); } public static void main(String[] args) { int[] arr = {4, 3, 2, 1, 6, 7}; int n = arr.length; int segSize = 2 * nextPowerOf2(n) - 1; int[] segment = new int[segSize]; Arrays.fill(segment, 0); buildSegmentTree(arr, segment, 0, n - 1, 0); printSegmentTree(segment); } }
Output
The output is as follows −
23 9 14 4 5 6 7 4 3 2 1 0 0 0
def nextPowerOf2(n): power = 1 while power < n: power *= 2 return power def buildSegmentTree(arr, segment, low, high, pos): if low == high: segment[pos] = arr[low] return mid = (low + high) // 2 buildSegmentTree(arr, segment, low, mid, 2 * pos + 1) buildSegmentTree(arr, segment, mid + 1, high, 2 * pos + 2) segment[pos] = segment[2 * pos + 1] + segment[2 * pos + 2] def printSegmentTree(segment): for i in segment: print(i, end = " ") print() arr = [4, 3, 2, 1, 6, 7] n = len(arr) segSize = 2 * nextPowerOf2(n) - 1 segment = [0] * segSize buildSegmentTree(arr, segment, 0, n - 1, 0) printSegmentTree(segment)
Output
Following is the output of the above code −
23 9 14 4 5 6 7 4 3 2 1 0 0 0
Applications of Segment Tree
Segment tree is used in various applications, such as:
- Range Sum Query
- Range Minimum/Maximum Query
- Range Update Query
- Range Count Query
Conclusion
In this tutorial, we have learned about the segment tree data structure. We have seen how the segment tree is built and how it is used to solve the range query problems. We have also seen the applications of the segment tree in various fields.