Proofs: Dynamic (sparse) segment tree
These are the human proofs of Dynamic (sparse) segment tree, at full length.
The dynamic segment tree keeps its invariant and answers range queries full
This proof shows: correctness, termination.
Let be a commutative monoid, , and let be the full segment tree over : the root covers , and a range with has the children and with . Each node of the dynamic tree corresponds to one range of , found by the walk from the root. Write , with .
Invariant (D). (a) The created nodes form a subtree of that contains the root. (b) Each created node over has . (c) If a range of has no created node, then for each in it.
At the start only the root exists with , and is all , so (D) holds.
Lemma 1 (termination of UPDATE). UPDATE with stops after passes of the loop, where is the depth of the leaf in , and holds at each pass.
Proof. Initially . If , the new range is , and otherwise it is . Each pass replaces a range of length by one of length or , so the length reaches 1 after at most passes, and the range is then .
Lemma 2 (UPDATE keeps (D)). After UPDATE the invariant holds for the new array with and for .
Proof. By Lemma 1, the loop visits exactly the ranges of that contain , from the root down to the leaf, and lines L7 and L10 create the missing ones, each as a child of a created node, so (a) holds. A node created at line L7 or L10 covers a range that had no node, so by (c) its items are all , and before line L3 adds . For each visited node, line L3 turns into , by commutativity and associativity, since . A node that is not visited covers a range without , so its value is unchanged and still right. A range without a node after the update does not contain , since every range with now has a node, so (c) holds for .
Lemma 3 (QUERY). For a created node over , or for an absent range of , and any , QUERY returns , read as when the range is empty.
Proof. By induction on . If , the range has no node, so by (c) every item in it is , and the result is right. If or , the overlap is empty and is right. If and , the overlap is and is right by (b). Otherwise the overlap is a proper part of , so , and the node has the two child ranges. A missing child is passed as 0, which is covered by the first case. The overlap with is the overlap with followed by the overlap with , so by the induction hypothesis and associativity line L15 returns the right value.
Theorem. After any sequence of updates, QUERY for , and the tree has at most nodes after updates.
Proof. The first part follows from Lemma 2 by induction over the updates and from Lemma 3 with the root, since . For the size, each update creates nodes only on one path of below the root, at most of them, and all created nodes are distinct nodes of , which has nodes.