Skip to main content

Segment Trees

Segment Tree Structure

Why Segment Trees?

Segment trees answer range queries and handle point/range updates in O(log n) time. They’re essential for problems involving:
  • Range sum/min/max/GCD queries
  • Range updates (add/set all elements)
  • Count elements in range satisfying condition
Pattern Recognition Signals:
  • “Query sum/min/max from L to R” → Segment tree
  • “Update element at position i” → Segment tree with point update
  • “Add x to all elements from L to R” → Lazy propagation
  • “Count elements > k in range” → Merge sort tree or segment tree with sets

Basic Segment Tree (Point Update, Range Query)

Usage


Segment Tree for Different Operations

Change the combine function and identity element.

Lazy Propagation (Range Updates)

When you need to update a range of elements, not just one. The Problem: Adding a value to all elements in range [L, R] would require O(R - L + 1) point updates, making it O(n) per update—too slow! The Insight: Don’t update immediately. Instead, store a “pending update” (lazy value) at a node. Only push it down to children when needed. How it works:
  1. Range Update: When updating [L, R], if a node’s range is completely inside [L, R], mark it with a lazy value and return (don’t recurse)
  2. Push Down: Before accessing children, push the lazy value down to them
  3. Query: Same as before, but push down lazy values as you traverse
Visual Example - Adding 5 to [1, 4] in array [1, 2, 3, 4, 5, 6]:
The lazy value is only pushed down when we need to access children.

Range Set (Assignment) with Lazy


Pattern 1: Coordinate Compression + Segment Tree

Problem: Count distinct elements, or handle values up to 10^9.

Pattern 2: Count Inversions with Segment Tree


Pattern 3: Range Queries Offline

Problem: Answer queries more efficiently by processing in smart order.

Pattern 4: Segment Tree on Indices

Problem: Track positions where something is true.

Pattern 5: 2D Segment Tree

For 2D range queries (less common, but powerful).

Common Mistakes

Mistake 1: Wrong array size Segment tree needs 4n space, not 2n.
Mistake 2: Forgetting to push lazy Always call pushDown before recursing in lazy segment tree.
Mistake 3: Wrong identity element
  • Sum: 0
  • Min: LLONG_MAX
  • Max: LLONG_MIN
  • GCD: 0
Mistake 4: 0-indexing vs 1-indexing Be consistent. The template above uses 0-indexed arrays.

Practice Problems

Beginner (1000-1300)

Intermediate (1300-1600)

Advanced (1600-1900)


Key Takeaways

O(log n) Queries

Both point updates and range queries in logarithmic time.

Lazy Propagation

Defer updates until needed for O(log n) range updates.

4n Space

Always allocate 4n space for the tree array.

Combine Function

Customize for sum, min, max, GCD, or any associative operation.

Next Up

Chapter 18: String Algorithms

Master hashing, KMP, Z-function, and Trie for string problems.