# Segment Tree

Last Updated : 03 Apr, 2024

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

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