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

Introduction to Segment Trees – Data Structure and Algorithm Tutorials

Similar Reads

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

Structure of the Tree

The segment tree works on the principle of divide and conquer....

Constructing the segment tree:

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

Range Query

Let us understand this with the help of the following problem...

Point Updates

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

Updating an interval (Lazy propagation):

...

Applications:

...

Advantages:

...

Disadvantages:

...

Contact Us