Segment Trees

advanced60 min

Segment Tree Overview

When the statement asks for many range queries or updates on a static or slowly changing array, a segment tree answers in O(log n) per operation instead of scanning the whole range each time.

Segment Tree Properties

  • Range Queries: O(log n) time for range operations
  • Point Updates: O(log n) time for single element updates
  • Range Updates: O(log n) time with lazy propagation
  • Space Complexity: O(n) space

Basic Segment Tree Implementation

Range Sum Query - Mutable

Segment Tree with Lazy Propagation

Common Applications

  • Range Sum: Sum of elements in a range
  • Range Min/Max: Minimum/maximum in a range
  • Range Updates: Add value to all elements in range
  • Inversion Count: Count inversions in array
  • 2D Problems: 2D segment trees for matrix operations