Lesson 42 of 86IntermediatePro Interactive Lesson

Segment Trees for Range Sums

Track which stored segments contribute to a query and which ancestors change after an update.

Core Intuition & How It Works

A segment tree is a binary tree over an array where each node stores an aggregate (sum, min, or max) of a contiguous subrange. It supports both point updates and arbitrary range queries in O(log n) time.

In the Byte Sized Algorithms interactive classroom, you can step forward and backward through this algorithm with your keyboard while watching the visual diagram, memory state, and highlighted pseudocode update together.

Time & Space Complexity

MetricComplexity
Time ComplexityO(n) build, O(log n) query/update
Space ComplexityO(n) (4n array)
Topic ChapterChapter 7: Trees
Difficulty LevelIntermediate

Key Pattern to Recognize

Split every query into total overlap (return node), no overlap (return identity), and partial overlap (recurse on both halves).

Common Pitfalls & Edge Cases

Returning 0 as the identity element for range-minimum queries instead of +Infinity, or under-allocating the tree array below 4n.

Real-World & Technical Interview Applications

Dynamic range sums/min/max, competitive programming, interval analytics, and computational geometry.

Unlock the full course

All 86 lessons across 15 chapters

View pricing

Delete account

This permanently deletes your account and ends any Pro access.