Module 09 · DSA · Four patterns the ladders lean on · about 22 min to read
Continue where you left off ×
A total for every half: segment trees and lazy updates
Rotations and Range Trees · Open board
The last tree on this board is the one this lesson builds: every node keeps the total of a stretch, so a question about a stretch reads a few nodes and nothing more.
Before you start. You need the segment tree sketch from Trees, Worked (rotations, B-trees, range trees) : a tree where each node holds the total of a stretch of a list, and the root holds the total of everything. The running total (prefix sums and difference arrays) gave you the prefix sum, a list of totals so far, where any stretch is one subtraction. Trees (BST, balancing, heaps, tries) gave you children and recursion on a tree. Complexity & Big-O gave you O(log n), which means the work grows by one step each time the list doubles.
The idea in 30 seconds
A segment tree stores the total of a stretch in every node, with 2n − 1 nodes for n numbers.
A range query covers the stretch with a few nodes and adds them, at most 4 per level.
A point update fixes only the nodes on one path from the number up to the root.
A range update on every number in a stretch is too slow done number by number.
Lazy propagation writes a tag on a covered node and pushes it down only when a later question looks inside.
Both free problems here, 307 and 2569, are this tree with a different thing stored in the nodes.
Read the story
Lesson 84 of 96 in DSA
The rest of this lesson is part of a plan.
A plan opens every lesson, board, video, lab and paper on chalk. Yearly is $39/year .
See plans Already a member? Sign in
Or start free : a free account opens lessons 2 and 3 of every track.
In this lesson 1994, Auckland: a table of counts that changes after every symbol Why the two old answers are both slow The segment tree: every node holds the total of a stretch The range query: cover the stretch with a few nodes The point update: fix only the nodes above one number The range update: why changing a whole stretch is a new problem Lazy propagation: leave a note, and pay it only when someone looks inside Storage and the four-times rule LeetCode 307, Range Sum Query, Mutable (free, Medium) The lazy tree: range add, range sum LeetCode 2569, Handling Sum Queries After Update (free, Hard) Edge cases and trade-offs Terms it explains: node, segment tree, range query, point update, range update, Lazy propagation, tag, Common mistakes.
Review DSA
Mark as read Saved in this browser, and to your account when you sign in.