Browse curriculum

Segment Tree

A segment tree is a tree data structure that stores intervals or segments, allowing efficient range queries and updates.

READY

The array underneath

1

0

3

1

5

2

7

3

9

4

11

5

 

Every node stores the sum of its range. Query a range to see how few of them the answer actually needs.

 

Array

Sum from

to

Set index

to

Intuition

If you have an array and need to find the sum of elements from index L to R frequently, a simple loop takes O(n). A Segment Tree precomputes partial sums in a tree structure, allowing both queries and updates in O(log n).

Concept

A Segment Tree is a full binary tree where each node represents an interval. The root represents the entire array [0, n-1]. Its children represent the left half [0, mid] and right half [mid+1, n-1]. Leaves represent individual elements [i, i].

How it Works

  • Build: Construct tree from array. tree[i] = tree[2*i] + tree[2*i+1] (for sum).
  • Query(L, R): Combine values from nodes that are fully within [L, R].
  • Update(i, val): Update leaf node for index i and recalculate values up to the root.
  • Range Update: (Advanced) Uses Lazy Propagation to defer updates for O(log n).

Step-by-Step Breakdown

Query Logic (Range Sum):
  1. Start at root covering [0, n-1].
  2. If node's range is completely inside [L, R], return node value.
  3. If node's range is completely outside [L, R], return 0.
  4. Otherwise, partial overlap: recurse left and right, then sum the results.

When to Use

  • Range queries (Sum, Min, Max, GCD) on an array.
  • When element updates are frequent (unlike Prefix Sum which is static).
  • Computational Geometry (finding intersecting rectangles).

When NOT to Use

  • When the array is static (use Prefix Sum Array for O(1) query).
  • When memory is extremely tight (approx 4n space).
  • When high-dimensional data is involved (KD-Tree might be better).

How to Identify

Keywords: "Range Sum Query", "Range Minimum Query", "Mutable Array", "Frequent Updates".

Applying for software engineering roles? Free, no sign-up:

AI resume checker — match your resume to the job description

Frequently Asked Questions

What are Segment Trees useful for?

They are used for range queries (Sum, Min, Max, GCD) and efficient updates on an underlying array in O(log n) time.


Segment Tree vs Fenwick Tree?

Segment Trees are more versatile as they can handle non-invertible operations (like Range Max). Fenwick Trees are more space-efficient and simpler to code for Range Sums.


What is the space complexity?

A Segment Tree typically requires O(4n) space where n is the number of elements in the base array.