Lesson contents

Segment trees

Group adjacent items into intervals. Store a summary, such as a maximum, for each interval so a query can use whole groups.

Simple example

Build maxima for the pairs 3,8 and 5,2. Combine their maxima to print the maximum for the whole interval.

Start3 8 5 2
Result8
Lesson.scala
object Lesson {
  def main(args: Array[String]): Unit = {
        var tree = Array(0, 0, 0, 0, 3, 8, 5, 2)
        var node = 3
        while (node > 0) {
            var left = tree(node * 2)
            var right = tree((node * 2) + 1)
            tree(node) = left
            if (right > left) {
                tree(node) = right
            }
            node -= 1
        }
        println(tree(1))
  }
}
Output
8
Advertisements

Everyday examples

Find the warmest afternoon

Hourly readings are 16, 22, 19 and 18. Which reading wins over all four hours?

Start16 22 / 19 18
Result22

Compare the two pair maxima, 22 and 19, to get the overall maximum.

Correct one shelf count

Counts are 3, 8, 5 and 2. Replace 8 with 1. What is the new maximum?

Start3 1 / 5 2
Result5

Update the changed leaf, its pair maximum and the top maximum. The other pair stays valid.

Query a middle interval

Daily bookings are 7, 2, 6 and 9. What is the largest count on days two and three?

Start7 [2 6] 9
Result6

Use only intervals inside the requested days. Including day four would incorrectly return 9.

Cost and limits

An associative summary can be combined over intervals. A point update and a standard contiguous range query each take O(log n).