The Wayback Machine - https://web.archive.org/web/20240913174428/https://www.geeksforgeeks.org/segment-tree-data-structure/
Open In App

Segment Tree

Last Updated : 03 Apr, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Segment Tree is a versatile data structure used in computer science and data structures that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree is built recursively by dividing the array into segments until each segment represents a single element. This structure enables fast query and update operations with a time complexity of O(log n), making it a powerful tool in algorithm design and optimization.

Segment-Tree-(1)

Segment Tree

What is Segment Tree?

Segment Tree is a data structure that stores data about range of elements in nodes as a tree. It is mostly used to handle range queries with updates in an efficient manner. For example, we can perform a range summation of an array between the range L to R while also modifying the array from range L to R all in log(N) time complexity.

Types of Operations:

The operations that the segment tree can perform must be binary and associative. Some of the examples of operations are:

  • Finding Range Sum Queries
  • Searching index with given prefix sum
  • Finding Range Maximum/Minimum
  • Counting frequency of Range Maximum/Minimum
  • Finding Range GCD/LCM
  • Finding Range AND/OR/XOR
  • Finding number of zeros in the given range or finding index of Kth zero

Applications of Segment Tree:

  • Interval scheduling: Segment trees can be used to efficiently schedule non-overlapping intervals, such as scheduling appointments or allocating resources.
  • Range-based statistics: Segment trees can be used to compute range-based statistics such as variance, standard deviation, and percentiles.
  • Image processing: Segment trees are used in image processing algorithms to divide an image into segments based on color, texture, or other attributes.

Basics of Segment Tree:

Lazy Propagation:

Range Queries:

Some interesting problem on Segment Tree:



Similar Reads

Find middle point segment from given segment lengths
Given an array arr[] of size M. The array represents segment lengths of different sizes. These segments divide a line beginning with 0. The value of arr[0] represents a segment from 0 arr[0], value of arr[1] represents segment from arr[0] to arr[1], and so on. The task is to find the segment which contains the middle point, If the middle segment do
6 min read
Build a segment tree for N-ary rooted tree
Prerequisite: Segment tree and depth first search.In this article, an approach to convert an N-ary rooted tree( a tree with more than 2 children) into a segment tree is discussed which is used to perform a range update queries. Why do we need a segment tree when we already have an n-ary rooted tree? Many times, a situation occurs where the same ope
15+ min read
Cartesian tree from inorder traversal | Segment Tree
Given an in-order traversal of a cartesian tree, the task is to build the entire tree from it. Examples: Input: arr[] = {1, 5, 3} Output: 1 5 3 5 / \ 1 3 Input: arr[] = {3, 7, 4, 8} Output: 3 7 4 8 8 / 7 / \ 3 4 Approach: We have already seen an algorithm here that takes O(NlogN) time on an average but can get to O(N2) in the worst case.In this art
13 min read
Comparison between Fenwick Tree vs Segment Tree - with Similarities and Differences
Fenwick Tree (Binary Indexed Tree) and Segment Tree are both data structures used for efficient range query and update operations on an array. Here's a tabular comparison of these two data structures. Similarities between the Fenwick tree and Segment treeHere are some of the areas where Fenwick Tree is similar to Segment Tree: Array type: Both Fenw
2 min read
Overview of Graph, Trie, Segment Tree and Suffix Tree Data Structures
Introduction:Graph: A graph is a collection of vertices (nodes) and edges that represent relationships between the vertices. Graphs are used to model and analyze networks, such as social networks or transportation networks.Trie: A trie, also known as a prefix tree, is a tree-like data structure that stores a collection of strings. It is used for ef
10 min read
Segment Tree | (XOR of a given range )
Let us consider the following problem to understand Segment Trees.We have an array arr[0 . . . n-1]. We should be able to 1 Find the xor of elements from index l to r where 0 <= l <= r <= n-1.2 Change value of a specified element of the array to a new value x. We need to do arr[i] = x where 0 <= i <= n-1.Similar to Sum of Given Range
15+ min read
Levelwise Alternating OR and XOR operations in Segment Tree
A Levelwise OR/XOR alternating segment tree is a segment tree, such that at every level the operations OR and XOR alternate. In other words at Level 1 the left and right sub-trees combine together by the OR operation i.e Parent node = Left Child OR Right Child and on Level 2 the left and right sub-trees combine together by the XOR operation i.e Par
15+ min read
Segment Tree | Set 2 (Range Maximum Query with Node Update)
Given an array arr[0 . . . n-1]. Find the maximum of elements from index l to r where 0 <= l <= r <= n-1. Also, change the value of a specified element of the array to a new value x. We need to do arr[i] = x where 0 <= i <= n-1 and then find the maximum element of given range with updated values.Example : Input : {1, 3, 5, 7, 9, 11}
15+ min read
Levelwise Alternating GCD and LCM of nodes in Segment Tree
A Levelwise GCD/LCM alternating segment tree is a segment tree, such that at every level the operations GCD and LCM alternate. In other words at Level 1 the left and right sub-trees combine together by the GCD operation i.e Parent node = Left Child GCD Right Child and on Level 2 the left and right sub-trees combine together by the LCM operation i.e
15+ min read
Iterative Segment Tree (Range Maximum Query with Node Update)
Given an array arr[0 . . . n-1]. The task is to perform the following operation: Find the maximum of elements from index l to r where 0 <= l <= r <= n-1.Change value of a specified element of the array to a new value x. Given i and x, change A[i] to x, 0 <= i <= n-1. Examples: Input: a[] = {2, 6, 7, 5, 18, 86, 54, 2} Query1: maximum(
14 min read
Iterative Segment Tree (Range Minimum Query)
We have discussed recursive segment tree implementation. In this post, iterative implementation is discussed.Let us consider the following problem understand Segment Trees. We have an array arr[0 . . . n-1]. We should be able to Find the minimum of elements from index l to r where 0 <= l <= r <= n-1 Change value of a specified element of t
14 min read
Counting inversions in an array using segment tree
Given an array of integers arr, the task is to count the number of inversions in the array. If A[i] > A[j] and i < j then the pair (A[i], A[j]) is part of an inversion. Examples: Input: arr[] = {8, 4, 2, 1} Output: 6 Input: arr[] = {3, 1, 2} Output: 2 Approach: Build a segment tree where each node will represent the total numbers present in t
10 min read
Range Update without using Lazy Propagation and Point Query in a Segment Tree
Given an array arr[] consisting of N 0s and a 2D array Q[][] consisting of queries of the following two types: 1 L R X: Increment all the elements in the range [L, R] by X.2 X: Print elements at Xth index of the array. Input: arr[] = { 0, 0, 0, 0, 0 }, Q[][] = { { 1, 0, 2, 100 }, { 2, 1 }, { 1, 2, 3, 200 }, { 2, 2 }, { 4 } } Output: 100 300 0 Expla
13 min read
Smallest subarray with GCD as 1 | Segment Tree
Given an array arr[], the task is to find the smallest sub-arrays with GCD equal to 1. If there is no such sub-array then print -1. Examples: Input: arr[] = {2, 6, 3} Output: 3 {2, 6, 3} is the only sub-array with GCD = 1. Input: arr[] = {2, 2, 2} Output: -1 Approach: This problem can be solved in O(NlogN) using a segment-tree data structure. The s
10 min read
Number of subarrays with GCD = 1 | Segment tree
Given an array arr[], the task is to find the count of sub-arrays with GCD equal to 1.Examples: Input: arr[] = {1, 1, 1} Output: 6 Every single subarray of the given array has GCD of 1 and there are a total of 6 subarrays.Input: arr[] = {2, 2, 2} Output: 0 Approach: This problem can be solved in O(NlogN) using segment-tree data structure. The segme
10 min read
Queries for greatest pair sum in the given index range using Segment Tree
Given an array arr[] containing N integers and an array Q[] representing the range [L, R], the task is to find the greatest pair sum value in the range [L, R] where 0 ? L ? R ? N - 1. Examples: Input: arr[] = {1, 3, 2, 7, 9, 11}, Q[] = {1, 4} Output: 16 Explanation: The greatest pair sum in range 1 to 4 is 7 + 9 = 16. Input: arr[] = {0, 1, 2, 3, 4,
14 min read
Maximum of all subarrays of size K using Segment Tree
Given an array arr[] and an integer K, the task is to find the maximum for each and every contiguous subarray of size K. Examples: Input: arr[] = {1, 2, 3, 1, 4, 5, 2, 3, 6}, K = 3 Output: 3 3 4 5 5 5 6 Explanation: Maximum of 1, 2, 3 is 3 Maximum of 2, 3, 1 is 3 Maximum of 3, 1, 4 is 4 Maximum of 1, 4, 5 is 5 Maximum of 4, 5, 2 is 5 Maximum of 5,
14 min read
Maximum sum possible for every node by including it in a segment of N-Ary Tree
Given an N-Ary tree containing N nodes and an array weight [ ] that denotes the weight of the nodes which can be positive or negative, the task for every node is to print the maximum sum possible by a sequence of nodes including the current node. Examples: Input: N = 7 weight[] = [-8, 9, 7, -4, 5, -10, -6] N-Ary tree: -8 / \ 9 7 / \ / -4 5 -10 / -6
13 min read
Length of Longest Increasing Subsequences (LIS) using Segment Tree
Given an array arr[] of size N, the task is to count the number of longest increasing subsequences present in the given array. Example: Input: arr[] = {2, 2, 2, 2, 2}Output: 5Explanation: The length of the longest increasing subsequence is 1, i.e. {2}. Therefore, count of longest increasing subsequences of length 1 is 5. Input: arr[] = {1, 3, 5, 4,
15+ min read
Applications, Advantages and Disadvantages of Segment Tree
First, let us understand why we need it prior to landing on the introduction so as to get why this concept was introduced. Suppose we are given an array and we need to find out the subarray Purpose of Segment Trees: A segment tree is a data structure that deals with a range of queries over an array. It has a divide and conquers approach. Used to so
4 min read
Queries for the count of even digit sum elements in the given range using Segment Tree.
Given an array arr[] of N elements, the task is to answer Q queries each having two integers L and R. For each query, the task is to find the number of elements in the subarray arr[L...R] whose digit sum is even.Examples: Input: arr[] = {7, 3, 19, 13, 5, 4} query = { 1, 5 } Output: 3 Explanation: Elements 19, 13 and 4 have even digit sum in the sub
15+ min read
Queries for elements greater than K in the given index range using Segment Tree
Given an array arr[] of N elements and a number of queries where each query will contain three integers L, R, and K. For each query, the task is to find the number of elements in the subarray arr[L...R] which are greater than K. Examples: Input: arr[] = {7, 3, 9, 13, 5, 4}, q[] = {{0, 3, 6}, {1, 5, 8}} Output: 3 2 Query 1: Only 7, 9 and 13 are grea
15+ min read
Segment Tree | Sum of given range
Let us consider the following problem to understand Segment Trees.We have an array arr[0 . . . n-1]. We should be able to Find the sum of elements from index l to r where 0 <= l <= r <= n-1Change the value of a specified element of the array to a new value x. We need to do arr[i] = x where 0 <= i <= n-1.Recommended PracticeSum of Que
15+ min read
Largest Rectangular Area in a Histogram using Segment Tree
Find the largest rectangular area possible in a given histogram where the largest rectangle can be made of a number of contiguous bars. For simplicity, assume that all bars have same width and the width is 1 unit. For example, consider the following histogram with 7 bars of heights {6, 2, 5, 4, 5, 1, 6}. The largest possible rectangle possible is 1
15+ min read
Lazy Propagation in Segment Tree
Segment tree is introduced in previous post with an example of range sum problem. We have used the same "Sum of given Range" problem to explain Lazy propagation How does update work in Simple Segment Tree? In the previous post, update function was called to update only a single value in array. Please note that a single value update in array may cau
15+ min read
Persistent Segment Tree | Set 1 (Introduction)
Prerequisite : Segment Tree Persistency in Data Structure Segment Tree is itself a great data structure that comes into play in many cases. In this post we will introduce the concept of Persistency in this data structure. Persistency, simply means to retain the changes. But obviously, retaining the changes cause extra memory consumption and hence a
15+ min read
Reconstructing Segment Tree
We are given 2*N - 1 integers. We need to check whether it is possible to construct a Range Minimum Query segment tree for an array of N distinct integers from these integers. If so, we must output the segment tree array. N is given to be a power of 2.An RMQ segment tree is a binary tree where each node is equal to the minimum value of its children
11 min read
Segment Tree | Set 3 (XOR of given range)
We have an array arr[0 . . . n-1]. There are two type of queries Find the XOR of elements from index l to r where 0 <= l <= r <= n-1Change value of a specified element of the array to a new value x. We need to do arr[i] = x where 0 <= i <= n-1. There will be total of q queries. Input Constraint n <= 10^5, q <= 10^5Recommended P
15+ min read
Segment tree | Efficient implementation
Let us consider the following problem to understand Segment Trees without recursion.We have an array arr[0 . . . n-1]. We should be able to, Find the sum of elements from index l to r where 0 <= l <= r <= n-1Change the value of a specified element of the array to a new value x. We need to do arr[i] = x where 0 <= i <= n-1. A simple s
12 min read
LIS using Segment Tree
You are given an array of integers, you need to find the length of the longest increasing sub-sequence. There can be 4 approaches for solving the problem. 1) Brute force: In this approach, we try to find all increasing subsequences and then returning the maximum length of longest increasing subsequence. In order to do this, we make use of a recursi
14 min read