The Convex Hull Trick & Li Chao Trees
When transitions are lines: the minimum of many lines in O(log n).
Shine a light up from below a set of lines: the shadow they cast is their lower envelope, and "which line is lowest at ?" is the question a whole family of DPs keeps asking. Answered naively it costs per query. With lines and queries in order it costs amortized , with queries out of order , and with nothing in order, Li Chao's segment tree of lines still answers in . Each step rests on one fact: two lines cross at most once.
What you’ll learn
- Prove that each line of a lower envelope is lowest on a single interval, in order of decreasing slope, and relate the envelope to the lower convex hull of the points .
- Prove the invariants and the amortized bound of the monotone convex hull trick, and answer out-of-order queries by binary search over the hull.
- Prove the Li Chao tree invariant, insert lines and query points in , and extend it to segments and to any functions that cross at most once.
- Derive the lower bound for building an envelope, and place dynamic envelopes and many-parameter transitions in the research landscape.
Lower envelopes and their shape
Intervals. Line is minimal at iff for every . Each condition is linear in , so it holds on a half-line, on all of , or nowhere, and an intersection of such sets is an interval:
Slope order. Suppose is minimal at and at . Then at and at , so this linear function does not decrease between them:
Concavity. A minimum of linear functions is concave. Two essential lines with equal slopes cannot both exist (the one with the larger intercept is never lowest), so the slopes of the essential lines strictly decrease and each owns one interval.
Why "convex hull". Read line as the point . Then , so the line lowest at minimizes a linear function over the points, and that minimum is attained at a vertex of their convex hull. Because the direction points upward, it is a vertex of the lower hull: the essential lines are exactly the vertices of the lower convex hull of the points (with some care at the two extreme slopes), listed by slope. Building the envelope is building a hull.
Which of the lines , and are essential in the lower envelope?
- All three
- only
- and only
- and only
Show the answer
C. and only
In slope order , , : and cross at , while and cross at . So takes over from before ever does; at , and are both at . The pop test agrees.
The monotone hull, proved
The Optimized lesson's deque inserts lines in order of decreasing slope at the back and answers queries in increasing order of at the front. Its correctness rests on one fact about three lines.
From , add the equations for and :
Both weights are positive, so lies between and . The middle line beats only right of and beats only left of , so it is strictly lowest somewhere iff , which by the average holds iff . The back pop when is exact.
Invariant. After each operation the deque holds, by decreasing slope, the lines of the envelope of everything inserted that are lowest somewhere on , where is the last query. Back pops remove lines that the new line makes inessential; a front pop removes a line that is lowest only left of , which no later query visits.
Cost. Every line is pushed once and popped at most once, from one end or the other, so insertions and queries take
Queries in any order. If only the slopes are sorted, build the hull with back pops alone and never pop the front. Along the hull, the values first decrease and then increase (the breakpoints are sorted), so binary search finds the lowest line in :
def query(hull, x): # hull: essential lines (m, b), by decreasing slope
lo, hi = 0, len(hull) - 1
while lo < hi:
mid = (lo + hi) // 2
m1, b1 = hull[mid]
m2, b2 = hull[mid + 1]
if m2 * x + b2 <= m1 * x + b1: # the envelope has already moved past line mid
lo = mid + 1
else:
hi = mid
m, b = hull[lo]
return m * x + bper query, with no assumption on the order of the queries. Tested against a brute-force minimum on random lines. If all queries are known in advance, sorting them restores the amortized front pops, at for the sort.
Li Chao trees: lines in any order
When lines arrive in arbitrary slope order and queries in arbitrary order, the deque breaks down. If the query points are integers in a known range , or can be compressed to one, a Li Chao tree needs no order at all. It is a segment tree over the range in which every node stores at most one line: the line that won at the node's midpoint when the node last saw a contest. It is named after Li Chao, who presented it in Chinese olympiad training material around 2012.
Insert a line at the root. If the node is empty, store it. Otherwise compare the new line with the stored one at the node's midpoint and keep the lower one there. The loser can still be lower only on one side of the midpoint, because two lines cross at most once: send it down to that child, and stop if it is lower on neither side. Query : walk from the root to the leaf containing and return the lowest of the stored lines at .
Induct on insertions. Before an insertion the invariant holds. Follow the new line down: at node with range and midpoint , the winner at stays and the loser continues. For points of 's range on the side not entered by , the two lines' difference has the same sign at as at the midpoint (they cross at most once, and on that side not at all):
So every path through that side keeps a line () at least as low as the discarded , and paths through the other side receive further down, by induction. The minimum along every path is the minimum over all lines.
Each step of an insertion or a query goes one level down a tree of depth , and an insertion creates at most one new node, the empty one where it stops:
class LiChao: # minimum of lines over integer x in [lo, hi)
def __init__(self, lo, hi):
self.lo, self.hi = lo, hi
self.line = {} # node -> (m, b); children of v are 2v and 2v+1
def insert(self, m, b, v=1, lo=None, hi=None):
if lo is None:
lo, hi = self.lo, self.hi
if v not in self.line:
self.line[v] = (m, b)
return
mid = (lo + hi) // 2
cm, cb = self.line[v]
if m * mid + b < cm * mid + cb: # the new line wins at mid: it stays here
self.line[v] = (m, b)
m, b, cm, cb = cm, cb, m, b # and the old line is the one sent down
if hi - lo == 1:
return
if m * lo + b < cm * lo + cb: # the loser wins at the left end: go left
self.insert(m, b, 2 * v, lo, mid)
elif m * (hi - 1) + b < cm * (hi - 1) + cb:
self.insert(m, b, 2 * v + 1, mid, hi)
def query(self, x):
v, lo, hi, best = 1, self.lo, self.hi, float('inf')
while v in self.line:
m, b = self.line[v]
best = min(best, m * x + b)
if hi - lo == 1:
break
mid = (lo + hi) // 2
v, lo, hi = (2 * v, lo, mid) if x < mid else (2 * v + 1, mid, hi)
return bestTested against a brute-force minimum over random lines and query points. Nodes are created lazily, so a range of costs about 30 levels and only memory. The proof never used that the functions are lines, only that two of them cross at most once: parabolas with the same leading coefficient work too.
A Li Chao node covers , with midpoint 8. Its stored line is lower at , but the new line is lower at . What happens to the new line?
- It replaces the stored line, since it is lower somewhere
- It is sent to the left child,
- It is sent to the right child,
- It is discarded, since it lost at the midpoint
Show the answer
B. It is sent to the left child,
The two lines cross once, between 0 and 8: left of the crossing the new line is lower, right of it the stored line is. The stored line keeps the node, and the new line continues into the left child, the only place it can still matter.
Segments. To insert a line that exists only on , split the range into the canonical nodes of the segment tree and run a line insertion from each: per segment.
A dynamic hull instead. A balanced search tree of lines ordered by slope, where each insertion deletes the neighbors it makes inessential (the three-line test again) and queries binary search on the breakpoints, needs no coordinate range and computes exact breakpoints: amortized per insertion and per query. Many team notebooks carry it as a "line container".
Lower bounds and the frontier
Given distinct numbers , take the tangent lines of the concave parabola at :
A tangent of a concave function lies above it and touches it only at its point, so at the line is strictly lower than every other tangent:
So every line is essential, and the envelope lists them by decreasing slope , that is, by increasing . Reading the envelope sorts the numbers, so the envelope inherits sorting's lower bound in that model.
Deletions. A DP rarely deletes lines, but offline problems and rollbacks do. Overmars and van Leeuwen (1981) maintained a planar convex hull under insertions and deletions in time per update, and Brodal and Jacob (2002) reached amortized per update with extreme-point queries, which in the dual are exactly "lowest line at " queries, matching a lower bound they proved. Contest solutions usually avoid deletions instead: a segment tree over time stores each line on the intervals of time when it exists, and a Li Chao tree with rollback answers the queries offline.
Segments, not lines. The lower envelope of segments can have pieces, where is the inverse Ackermann function, by the theory of Davenport–Schinzel sequences, and Hershberger (1989) computed it in time.
Key takeaways
- On the lower envelope of lines, each essential line is lowest on one interval, in order of decreasing slope; the essential lines are the vertices of the lower convex hull of the points .
- The monotone hull pops a middle line exactly when , since is a weighted average of and ; every line is pushed and popped once, so insertions and queries cost .
- Without sorted queries, binary search over the hull costs per query; without sorted slopes either, a Li Chao tree costs per operation, because two lines cross at most once.
- Building an envelope of arbitrary lines sorts, so holds in the algebraic decision tree model; with many parameters per transition, the problem becomes as hard as minimum inner product.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Reading each line as the point , which points correspond to the essential lines of the lower envelope?
- The vertices of the lower convex hull of the points
- The vertices of the upper convex hull of the points
- The points with the smallest intercepts
- All of the points
Show the answer
A. The vertices of the lower convex hull of the points
, so the lowest line at minimizes a linear function over the points, which happens at a hull vertex; the direction points upward, so the minimizing vertex lies on the lower hull.
The monotone convex hull trick processes insertions (slopes decreasing) and queries ( increasing). What is the total running time?
Show the answer
C.
One insertion or query can pop many lines, but each line is pushed once and popped at most once over the whole run, so the pops total at most and the work is .
Query points are integers in , and lines arrive in arbitrary order of slope. What does a Li Chao tree cost for insertions and queries?
- time, about 30 steps per operation, and nodes
- time
- memory for the tree
- time, since each query checks every line
Show the answer
A. time, about 30 steps per operation, and nodes
Each operation walks one root-to-leaf path of depth , and nodes are created only when a line stops in an empty one, at most one per insertion.
Why can no algorithm in the algebraic decision tree model build the lower envelope of arbitrary lines in time?
- Because the envelope can have pieces
- Because the tangent lines of a parabola at are all essential and appear in sorted order of the , so building the envelope sorts
- Because computing each crossing point needs a division
- It can: the monotone hull builds any envelope in
Show the answer
B. Because the tangent lines of a parabola at are all essential and appear in sorted order of the , so building the envelope sorts
Sorting numbers reduces to building an envelope, so the envelope inherits sorting's bound in that model.
Further reading
- M. Ben-Or, "Lower bounds for algebraic computation trees," Proceedings of the 15th ACM Symposium on Theory of Computing (1983).
- M. H. Overmars & J. van Leeuwen, "Maintenance of configurations in the plane," Journal of Computer and System Sciences 23 (1981).
- G. S. Brodal & R. Jacob, "Dynamic planar convex hull," Proceedings of the 43rd IEEE Symposium on Foundations of Computer Science (2002).
- J. Hershberger, "Finding the upper envelope of n line segments in O(n log n) time," Information Processing Letters 33 (1989).
- CP-Algorithms, "Convex hull trick and Li Chao tree".