top of page

Understanding Segment Tree Basics

  • Writer: Samvar Shah
    Samvar Shah
  • Jan 15
  • 2 min read

What is a Segment Tree?

A Segment Tree is a binary tree used for storing intervals (ranges) or segments. Each node in the tree represents a segment of the array and the leaf nodes correspond to individual elements. The internal nodes store information about the union or aggregation of the segments below them depending on the problem's needs.


Segment trees are ideal for problems where we need to:

  • Query the sum, minimum, or maximum of elements and update values stored and propagate the change efficiently.

  • It is also used for problems involving point update, range query and range update point query


Key Operations

  1. Build: Constructing the segment tree takes O(n) time, where n is the number of elements in the array. This is done by recursively dividing the array into two halves, storing the result at each node.

  2. Query: A range query can be answered in O(log n) time. Instead of scanning the entire range, the segment tree efficiently navigates the relevant nodes, combining their values to give the result.

  3. Update: An update to an element in the array can be processed in O(log n) time, by updating the leaf node and then adjusting the corresponding internal nodes to reflect the change.


Problem: Range Sum Query

Given an array of integers and need to (frequently) calculate the sum of elements in a given range [l, r]. A basic approach would involve iterating over the array for each query which takes O(r - l) time. But if we have many queries, this becomes inefficient.


A Segment Tree allows us to:

  • Build the tree in O(n) time.

  • Answer each sum query in O(log n) time, making it suitable for large arrays and numerous queries.


Comments

Rated 0 out of 5 stars.
No ratings yet

Add a rating
bottom of page