Open in App
Not now

# Introduction to Segment Trees – Data Structure and Algorithm Tutorials

• Difficulty Level : Hard
• Last Updated : 15 Mar, 2023

## What is Segment Tree?

A Segment Tree is a data structure that stores information about a range of elements in its nodes. It also allows users to modify the array and perform range queries in smaller complexity. 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. Overall the values must belong to the set of the semigroup. The neutral element must be obvious according to the type of operation and semigroup we are looking for. For example, if we want to find the sum over the range of values in an array where the elements belong to  then the neutral element, in this case, will be 0. Some of the examples of operations are:

• Maximum/Minimum
• GCD/LCM

## Structure of the Tree

The segment tree works on the principle of divide and conquer

• At each level, we divide the array segments into two parts. If the given array had [0, . . ., N-1] elements in it then the two parts of the array will be [0, . . ., N/2-1] and [N/2, . . ., N-1]
• We will then recursively go on until the lower and upper bounds of the range become equal.
• The structure of the segment tree looks like a binary tree.

The segment tree is generally represented using an array where the first value stores the value for the total array range and the child of the node at ith index are at (2*i + 1) and (2*i + 2).

## Constructing the segment tree:

There are two important points to be noted while constructing the segment tree:

• Choosing what value to be stored in the nodes according to the problem definition
• What should the merge operation do

If the problem definition states that we need to calculate the sum over ranges, then the value at nodes should store the sum of values over the ranges.

• The child node values are merged back into the parent node to hold the value for that particular range, [i.e., the range covered by all the nodes of its subtree].
• In the end, leaf nodes store information about a single element. All the leaf nodes store the array based on which the segment tree is built.

Following are the steps for constructing a segment tree:

1. Start from the leaves of the tree
2. Recursively build the parents from the merge operation

The merge operation will take constant time if the operator takes constant time. SO building the whole tree takes O(N) time.

Segment tree

## Range Query

Let us understand this with the help of the following problem

Given two integers L and R return the sum of the segment [L, R]

The first step is constructing the segment tree with the addition operator and 0 as the neutral element.

• If the range is one of the node’s range values then simply return the answer.
• Otherwise, we will need to traverse the left and right children of the nodes and recursively continue the process till we find a node that covers a range that totally covers a part or whole of the range [L, R]
• While returning from each call, we need to merge the answers received from each of its child.

As the height of the segment tree is logN the query time will be O(logN) per query.

Range Query in Segment Tree

Given an index,  idx, update the value of the array at index idx with value V

The element’s contribution is only in the path from its leaf to its parent. Thus only logN elements will get affected due to the update.

For updating, traverse till the leaf that stores the value of index idx and update the value. Then while tracing back in the path, modify the ranges accordingly.

The time complexity will be O(logN).

Point Update in Segment Tree

Below is the implementation of construction, query and point update for a segment tree:

## C++

 // C++ code for segment tree with sum // range and update query    #include using namespace std; vector A, ST;    void build(int node, int L, int R) {        // Leaf node where L == R     if (L == R) {         ST[node] = A[L];     }     else {            // Find the middle element to         // split the array into two halves         int mid = (L + R) / 2;            // Recursively travel the         // left half         build(2 * node, L, mid);            // Recursively travel the         // right half         build(2 * node + 1, mid + 1, R);            // Storing the sum of both the         // children into the parent         ST[node] = ST[2 * node] + ST[2 * node + 1];     } }    void update(int node, int L, int R, int idx, int val) {        // Find the lead node and     // update its value     if (L == R) {         A[idx] += val;         ST[node] += val;     }     else {            // Find the mid         int mid = (L + R) / 2;            // If node value idx is at the         // left part then update         // the left part         if (L <= idx and idx <= mid)             update(2 * node, L, mid, idx, val);         else             update(2 * node + 1, mid + 1, R, idx, val);            // Store the information in parents         ST[node] = ST[2 * node] + ST[2 * node + 1];     } }    int query(int node, int tl, int tr, int l, int r) {        // If it lies out of range then     // return 0     if (r < tl or tr < l)         return 0;        // If the node contains the range then     // return the node value     if (l <= tl and tr <= r)         return ST[node];     int tm = (tl + tr) / 2;        // Recursively traverse left and right     // and find the node     return query(2 * node, tl, tm, l, r)            + query(2 * node + 1, tm + 1, tr, l, r); }    // Driver code int main() {     int n = 6;     A = { 0, 1, 3, 5, -2, 3 };        // Create a segment tree of size 4*n     ST.resize(4 * n);        // Build a segment tree     build(1, 0, n - 1);     cout << "Sum of values in range 0-4 are: "          << query(1, 0, n - 1, 0, 4) << "\n";        // Update the value at idx = 1 by     // 100 thus becoming 101     update(1, 0, n - 1, 1, 100);     cout << "Value at index 1 increased by 100\n";     cout << "sum of value in range 1-3 are: "          << query(1, 0, n - 1, 1, 3) << "\n";        return 0; }

## Java

 // Java code for segment tree with sum // range and update query import java.io.*; import java.util.*;    class GFG {     static int n = 6;     static int A[] = { 0, 1, 3, 5, -2, 3 };        // Create a segment tree of size 4*n     static int ST[] = new int[4 * n];     public static void build(int node, int L, int R)     {            // Leaf node where L == R         if (L == R) {             ST[node] = A[L];         }         else {                // Find the middle element to             // split the array into two halves             int mid = (L + R) / 2;                // Recursively travel the             // left half             build(2 * node, L, mid);                // Recursively travel the             // right half             build(2 * node + 1, mid + 1, R);                // Storing the sum of both the             // children into the parent             ST[node] = ST[2 * node] + ST[2 * node + 1];         }     }        public static void update(int node, int L, int R,                               int idx, int val)     {            // Find the lead node and         // update its value         if (L == R) {             A[idx] += val;             ST[node] += val;         }         else {                // Find the mid             int mid = (L + R) / 2;                // If node value idx is at the             // left part then update             // the left part             if (L <= idx && idx <= mid)                 update(2 * node, L, mid, idx, val);             else                 update(2 * node + 1, mid + 1, R, idx, val);                // Store the information in parents             ST[node] = ST[2 * node] + ST[2 * node + 1];         }     }        public static int query(int node, int tl, int tr, int l,                             int r)     {            // If it lies out of range then         // return 0         if (r < tl || tr < l)             return 0;            // If the node contains the range then         // return the node value         if (l <= tl && tr <= r)             return ST[node];         int tm = (tl + tr) / 2;            // Recursively traverse left and right         // and find the node         return query(2 * node, tl, tm, l, r)             + query(2 * node + 1, tm + 1, tr, l, r);     }        // Driver Code     public static void main(String[] args)     {         // Build a segment tree         build(1, 0, n - 1);         System.out.println(             "Sum of values in range 0-4 are: "             + query(1, 0, n - 1, 0, 4));            // Update the value at idx = 1 by         // 100 ths becoming 101         update(1, 0, n - 1, 1, 100);         System.out.println(             "Value at index 1 increased by 100");         System.out.println("sum of value in range 1-3 are: "                            + query(1, 0, n - 1, 1, 3));     } }    // This code is contributed by Rohit Pradhan

## Python3

 # python3 code for segment tree with sum # range and update query A = [] ST = []    def build(node, L, R):     global A, ST        # Leaf node where L == R     if (L == R):         ST[node] = A[L]        else:            # Find the middle element to         # split the array into two halves         mid = (L + R) // 2            # Recursively travel the         # left half         build(2 * node, L, mid)            # Recursively travel the         # right half         build(2 * node + 1, mid + 1, R)            # Storing the sum of both the         # children into the parent         ST[node] = ST[2 * node] + ST[2 * node + 1]       def update(node, L, R, idx, val):     global A, ST        # Find the lead node and     # update its value     if (L == R):         A[idx] += val         ST[node] += val        else:            # Find the mid         mid = (L + R) // 2            # If node value idx is at the         # left part then update         # the left part         if (L <= idx and idx <= mid):             update(2 * node, L, mid, idx, val)         else:             update(2 * node + 1, mid + 1, R, idx, val)            # Store the information in parents         ST[node] = ST[2 * node] + ST[2 * node + 1]       def query(node, tl, tr, l, r):     global A, ST        # If it lies out of range then     # return 0     if (r < tl or tr < l):         return 0        # If the node contains the range then     # return the node value     if (l <= tl and tr <= r):         return ST[node]     tm = (tl + tr) // 2        # Recursively traverse left and right     # and find the node     return query(2 * node, tl, tm, l, r) + query(2 * node + 1, tm + 1, tr, l, r)    # Driver code if __name__ == "__main__":        n = 6     A = [0, 1, 3, 5, -2, 3]        # Create a segment tree of size 4*n     ST = [0 for _ in range(4 * n)]        # Build a segment tree     build(1, 0, n - 1)     print(f"Sum of values in range 0-4 are: {query(1, 0, n - 1, 0, 4)}")        # Update the value at idx = 1 by     # 100 ths becoming 101     update(1, 0, n - 1, 1, 100)     print("Value at index 1 increased by 100")     print(f"sum of value in range 1-3 are: {query(1, 0, n - 1, 1, 3)}")        # This code is contributed by rakeshsahni

## C#

 // C# code for segment tree with sum // range and update query    using System;    public class GFG {      static int n = 6;   static int[] A = { 0, 1, 3, 5, -2, 3 };      // Create a segment tree of size 4*n   static int[] ST = new int[4 * n];      public static void build(int node, int L, int R)   {        // Leaf node where L == R     if (L == R) {       ST[node] = A[L];     }     else {          // Find the middle element to       // split the array into two halves       int mid = (L + R) / 2;          // Recursively travel the       // left half       build(2 * node, L, mid);          // Recursively travel the       // right half       build(2 * node + 1, mid + 1, R);          // Storing the sum of both the       // children into the parent       ST[node] = ST[2 * node] + ST[2 * node + 1];     }   }      public static void update(int node, int L, int R,                             int idx, int val)   {        // Find the lead node and     // update its value     if (L == R) {       A[idx] += val;       ST[node] += val;     }     else {          // Find the mid       int mid = (L + R) / 2;          // If node value idx is at the       // left part then update       // the left part       if (L <= idx && idx <= mid)         update(2 * node, L, mid, idx, val);       else         update(2 * node + 1, mid + 1, R, idx, val);          // Store the information in parents       ST[node] = ST[2 * node] + ST[2 * node + 1];     }   }      public static int query(int node, int tl, int tr, int l,                           int r)   {        // If it lies out of range then     // return 0     if (r < tl || tr < l)       return 0;        // If the node contains the range then     // return the node value     if (l <= tl && tr <= r)       return ST[node];     int tm = (tl + tr) / 2;        // Recursively traverse left and right     // and find the node     return query(2 * node, tl, tm, l, r)       + query(2 * node + 1, tm + 1, tr, l, r);   }      static public void Main()   {        // Code     // Build a segment tree     build(1, 0, n - 1);     Console.WriteLine("Sum of values in range 0-4 are: "                       + query(1, 0, n - 1, 0, 4));        // Update the value at idx = 1 by     // 100 ths becoming 101     update(1, 0, n - 1, 1, 100);     Console.WriteLine(       "Value at index 1 increased by 100");     Console.WriteLine("sum of value in range 1-3 are: "                       + query(1, 0, n - 1, 1, 3));   } }    // This code is contributed by lokeshmvs21.

## Javascript

 // JavaScript code for the above approach        function build(node, L, R)        {                      // Leaf node where L == R            if (L === R) {                ST[node] = A[L];            } else {                // Find the middle element to split the array into two halves                const mid = Math.floor((L + R) / 2);                  // Recursively travel the left half                build(2 * node, L, mid);                  // Recursively travel the right half                build(2 * node + 1, mid + 1, R);                  // Storing the sum of both the children into the parent                ST[node] = ST[2 * node] + ST[2 * node + 1];            }        }          function update(node, L, R, idx, val)        {                      // Find the lead node and update its value            if (L === R) {                A[idx] += val;                ST[node] += val;            } else {                // Find the mid                const mid = Math.floor((L + R) / 2);                  // If node value idx is at the left part then update the left part                if (L <= idx && idx <= mid) {                    update(2 * node, L, mid, idx, val);                } else {                    update(2 * node + 1, mid + 1, R, idx, val);                }                  // Store the information in parents                ST[node] = ST[2 * node] + ST[2 * node + 1];            }        }          function query(node, tl, tr, l, r) {            // If it lies out of range then return 0            if (r < tl || tr < l) return 0;              // If the node contains the range then return the node value            if (l <= tl && tr <= r) return ST[node];            const tm = Math.floor((tl + tr) / 2);              // Recursively traverse left and right and find the node            return query(2 * node, tl, tm, l, r) + query(2 * node + 1, tm + 1, tr, l, r);        }          // Driver Code        const A = [0, 1, 3, 5, -2, 3];        const ST = new Array(4 * A.length);        // Build a segment tree        build(1, 0, A.length - 1);        console.log(`Sum of values in range 0-4 are: \${query(1, 0, A.length - 1, 0, 4)}
`);          // Update the value at idx = 1 by 100 thus becoming 101        update(1, 0, A.length - 1, 1, 100);        console.log(`Value at index 1 increased by 100
`);        console.log(`sum of value in range 1-3 are: \${query(1, 0, A.length - 1, 1, 3)}
`);   // This code is contributed by Potta Lokesh

Output

Sum of values in range 0-4 are: 7
Value at index 1 increased by 100
sum of value in range 1-3 are: 109

Time complexity: O(N)

• The building operation takes O(N) time
• The query operation takes O(logN) time
• Each update is performed in O(logN) time

Auxiliary Space: O(n)

## Updating an interval (Lazy propagation):

Lazy Propagation: A speedup technique for range updates

Example of segment tree

• We can delay some updates (avoid recursive calls in update) and do such updates only when necessary when there are several updates and updates are being performed on a range.
• A node in a segment tree stores or displays the results of a query for a variety of indexes.
• Additionally, all of the node’s descendants must also be updated if the update operation’s range includes this node.
• Take the node with the value 27 in the picture above as an example. This node contains the sum of values at the indexes 3 to 5. This node and all of its descendants must be updated if our update query covers the range of 2 to 5.
• By storing this update information in distinct nodes referred to as lazy nodes or values, we use lazy propagation to update only the node with value 27 and delay updates to its descendants.
• We make an array called lazy[] to stand in for the lazy node. The size of lazy[] is the same as the array used to represent the segment tree in the code following, which is tree[].
• The goal is to set all of the lazy[elements] to 0.
• There are no pending changes on the segment tree node i if lazy[i] has a value of 0.
• A non-zero value for lazy[i] indicates that before doing any queries on node i in the segment tree, this sum needs to be added to the node.

Below is the implementation to demonstrate the working of Lazy Propagation.

## Javascript

Output

Sum of values in given range = 15
Updated sum of values in given range = 45

Time Complexity: O(N)
Auxiliary Space: O(MAX)

## Applications:

• 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.

• Efficient querying: Segment trees can be used to efficiently answer queries about the minimum, maximum, sum, or other aggregate value of a range of elements in an array.
• Efficient updates: Segment trees can be used to efficiently update a range of elements in an array, such as incrementing or decrementing a range of values.
• Flexibility: Segment trees can be used to solve a wide variety of problems involving range queries and updates.