Segment Tree

Segment tree is a data structure that supports queries and update on intervals.

It can be used for solving range query problems like finding minimum, maximum, sum, greatest common divisor, least common denominator in array in logarithmic time.

Segment Tree
Node values in a segment tree used in range sum query

Example range sum query problem:

given an array, you need to do the following operations:

  • add k to every numbers in a index range.

  • get the sum of all the numbers within a index range.

The merge operation can be sum or any operation that satisfies associative law.

Implementation

Here I use 307. Range Sum Query - Mutable (Medium) as an example.

Another OOD implementation:

Lazy Propogation

When we want to update an interval all at once, we need to use lazy propagation to ensure good run-time complexity.

Problems

Reference

Last updated

Was this helpful?