Sub topic 7
The Max-Endpoint Invariant
This chapter assumes you can write BST insertion and search, you know that operations cost O(h) for a tree of height h, and you are comfortable with short recursive Python functions. It also assumes you have seen the closed-interval overlap test from earlier in this tutorial.
What the invariant says
Each node of an interval tree stores one interval [lo, hi]. The tree is ordered by lo, exactly like keys in an ordinary BST. The augmentation is one extra field per node, max.
The invariant is:
- For every node
x,x.maxequals the largesthivalue among all intervals stored in the subtree rooted atx, includingxitself.
Equivalently, x.max is the larger of three values: x.hi, x.left.max, and x.right.max. A missing child contributes nothing, which you can model as negative infinity.
Two details cause most early confusion:
maxis a maximum of high endpoints, not of low endpoints. The BST key islo, andmaxis a separate fact abouthivalues.maxdescribes the subtree, not the whole tree. Only the root'smaxis a global maximum.
Why this field is useful
Ordering by lo tells you where a node sits, but it says nothing about how far the intervals in a subtree reach to the right. A left subtree may hold intervals with small lo values and very large hi values. Without extra information you would have to visit all of them to find out.
The max field answers one question in constant time: does any interval in this subtree reach at least as far right as the query's lo? If left.max < lo, every interval in the left subtree ends before the query begins, so none can overlap it, and the whole subtree can be skipped. The next chapters build the search on this one fact.
A worked example
Insert these intervals in order: (15, 20), (10, 30), (17, 19), (5, 20), (12, 15), (30, 40). The resulting tree, with each node's max computed from the rule above, looks like this:
Check a few nodes by hand:
- The leaf (12, 15) has no children, so its
maxis its ownhi, which is 15. - The node (10, 30) has
hi30, leftmax20, and rightmax15. The largest is 30. - The node (17, 19) has
hi19 and a right child withmax40. Itsmaxis 40 even though its ownhiis only 19. - The root takes 40 from its right subtree.
Maintaining the field in code
Recomputing a node's max from its own hi and its children's max values is a constant-time operation. Putting it in one helper keeps every later operation (insertion, deletion, rotation) consistent.
NEG_INF = float("-inf")
class Node:
def __init__(self, lo, hi):
self.lo = lo
self.hi = hi
self.max = hi
self.left = None
self.right = None
def update_max(node):
# Recompute node.max from its own hi and its children's max values.
left_max = node.left.max if node.left is not None else NEG_INF
right_max = node.right.max if node.right is not None else NEG_INF
node.max = max(node.hi, left_max, right_max)
def insert(node, lo, hi):
if node is None:
return Node(lo, hi)
if lo < node.lo:
node.left = insert(node.left, lo, hi)
else:
node.right = insert(node.right, lo, hi)
update_max(node)
return node
def verify(node):
# Return the true largest hi in the subtree; raise if a stored max is wrong.
if node is None:
return NEG_INF
true_max = max(node.hi, verify(node.left), verify(node.right))
if node.max != true_max:
raise AssertionError(
f"bad max at ({node.lo}, {node.hi}): stored {node.max}, true {true_max}"
)
return true_max
root = None
for lo, hi in [(15, 20), (10, 30), (17, 19), (5, 20), (12, 15), (30, 40)]:
root = insert(root, lo, hi)
print(verify(root)) # 40
print(root.left.max, root.right.max) # 30 40
root.left.max = 25 # deliberately corrupt one node
try:
verify(root)
except AssertionError as err:
print(err) # bad max at (10, 30): stored 25, true 30The verify function is a test aid, not part of the data structure. It rebuilds the true value bottom-up in O(n) time and compares it with the stored one. Calling it after a batch of random inserts and deletes is a cheap way to catch bugs in your update logic.
The insert here recomputes max from the children instead of using node.max = max(node.max, hi). Both work for insertion, because insertion can only raise a subtree's maximum. The recompute version is the one you will reuse for deletion and rotations, where a maximum can fall.
Why updates stay cheap
A node's max depends only on its own hi and its two children. This local dependence is what makes the augmentation practical. Changing one node can only affect the max of that node's ancestors, so after any modification you walk back up one root-to-node path and recompute each node once.
| Operation | Nodes whose `max` may change | Extra cost |
|---|---|---|
| Insert | Ancestors of the new leaf | O(1) per ancestor, O(h) total |
| Delete | Ancestors of the removed position | O(1) per ancestor, O(h) total |
| Rotation | The two nodes rotated, then ancestors | O(1) for the rotation itself |
| Search | None (read only) | None |
The cost of the field is one extra number per node, so space grows by a constant factor and the O(h) bounds of the plain BST are preserved.
Edge cases
- Equal low endpoints. The BST ordering may send duplicates left or right, and the invariant does not care. It depends only on
hivalues, never on how ties inloare broken. - A node with a small
hiand a large subtree. As the (17, 19) node shows,node.maxcan be larger thannode.hi. Never assume the two are equal for internal nodes. - Empty children. Handle
Noneexplicitly. Readingnode.left.maxon a missing child raises anAttributeError. - Intervals that are single points. (7, 7) is a valid closed interval with
lo == hi. It needs no special treatment.
Common mistakes
- Updating only the new node's
maxduring insertion and forgetting its ancestors. - Storing the maximum
loinstead of the maximumhi. - Computing
maxonly from the children and forgetting the node's ownhi. - Updating ancestors in top-down order. Each node depends on its children, so the update must run bottom-up, which the recursion in
insertdoes as it returns. - Skipping the update after a rotation, which is covered in the chapter on balancing.
Exercise
A node has interval (8, 12). Its left child has max 20 and its right child is missing. What is the node's max? Then you delete the left child's whole subtree, whose largest high endpoint was 20, so the node has no children left. What is the node's max after you recompute it?
Show answer
Before the deletion the max is max(12, 20) = 20. After the deletion the node has no children, so its max is its own hi, which is 12. The max went down, which is why deletion must recompute from the children and cannot just keep the old value.
Exercise
In the example tree, the interval (12, 15) is deleted and its leaf is removed. Which nodes have their max recomputed, and what are their new values?
Show answer
Only the ancestors of the removed leaf change: (10, 30) and the root (15, 20). The node (10, 30) has hi 30 and one remaining child, (5, 20) with max 20, so its max stays 30. The root's children have max 30 and 40, so its max stays 40. The recomputation is still needed, because in general a max can drop. Here both values happen to be unchanged.