Simple Algorithm
Algorithms & Data Structures · Optimal · 28 min

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 xx?" is the question a whole family of DPs keeps asking. Answered naively it costs O(n)O(n) per query. With lines and queries in order it costs amortized O(1)O(1), with queries out of order O(log⁡n)O(\log n), and with nothing in order, Li Chao's segment tree of lines still answers in O(log⁡C)O(\log C). 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 (m,b)(m, b).
  • 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 O(log⁡C)O(\log C), and extend it to segments and to any functions that cross at most once.
  • Derive the Ω(nlog⁡n)\Omega(n \log n) lower bound for building an envelope, and place dynamic envelopes and many-parameter transitions in the research landscape.

Lower envelopes and their shape

DerivationProof
  1. {x:ℓj(x)≤ℓk(x) ∀k}=⋂k{x:(mj−mk) x≤bk−bj}\{x : \ell_j(x) \le \ell_k(x)\ \forall k\} = \bigcap_k \{x : (m_j - m_k)\,x \le b_k - b_j\}

    Intervals. Line jj is minimal at xx iff ℓj(x)≤ℓk(x)\ell_j(x) \le \ell_k(x) for every kk. Each condition is linear in xx, so it holds on a half-line, on all of R\mathbb{R}, or nowhere, and an intersection of such sets is an interval:

  2. (mj−mk)(x′−x)≥0  ⟹  mj≥mk(m_j - m_k)(x' - x) \ge 0 \;\Longrightarrow\; m_j \ge m_k

    Slope order. Suppose ℓj\ell_j is minimal at xx and ℓk\ell_k at x′>xx' > x. Then ℓj−ℓk≤0\ell_j - \ell_k \le 0 at xx and ≥0\ge 0 at x′x', so this linear function does not decrease between them:

  3. E(θx+(1−θ)x′)≥θE(x)+(1−θ)E(x′)E(\theta x + (1-\theta)x') \ge \theta E(x) + (1-\theta)E(x')

    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 jj as the point pj=(mj,bj)p_j = (m_j, b_j). Then ℓj(x)=⟨pj,(x,1)⟩\ell_j(x) = \langle p_j, (x, 1)\rangle, so the line lowest at xx minimizes a linear function over the points, and that minimum is attained at a vertex of their convex hull. Because the direction (x,1)(x, 1) 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 (mj,bj)(m_j, b_j) (with some care at the two extreme slopes), listed by slope. Building the envelope is building a hull.

Check your understanding

Which of the lines A:y=x+3A: y = x + 3, B:y=4B: y = 4 and C:y=−2x+5C: y = -2x + 5 are essential in the lower envelope?

  1. All three
  2. BB only
  3. AA and CC only
  4. AA and BB only
Show the answer

C. AA and CC only

In slope order AA, BB, CC: AA and BB cross at xAB=1x_{AB} = 1, while AA and CC cross at xAC=2/3≤xABx_{AC} = 2/3 \le x_{AB}. So CC takes over from AA before BB ever does; at x=2/3x = 2/3, AA and CC are both at 11/3<411/3 < 4. The pop test (bC−bA)(mA−mB)=2≤(bB−bA)(mA−mC)=3(b_C - b_A)(m_A - m_B) = 2 \le (b_B - b_A)(m_A - m_C) = 3 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 xx at the front. Its correctness rests on one fact about three lines.

DerivationProof and invariants
  1. (m1−m3) x13=(m1−m2) x12+(m2−m3) x23(m_1 - m_3)\,x_{13} = (m_1 - m_2)\,x_{12} + (m_2 - m_3)\,x_{23}

    From (ma−mb) xab=bb−ba(m_a - m_b)\,x_{ab} = b_b - b_a, add the equations for (1,2)(1, 2) and (2,3)(2, 3):

  2. ℓ2 essential  ⟺  x12<x23  ⟺  x12<x13\ell_2 \text{ essential} \iff x_{12} < x_{23} \iff x_{12} < x_{13}

    Both weights are positive, so x13x_{13} lies between x12x_{12} and x23x_{23}. The middle line beats ℓ1\ell_1 only right of x12x_{12} and beats ℓ3\ell_3 only left of x23x_{23}, so it is strictly lowest somewhere iff x12<x23x_{12} < x_{23}, which by the average holds iff x12<x13x_{12} < x_{13}. The back pop when x13≤x12x_{13} \le x_{12} is exact.

  3. deque=envelope of the inserted lines, restricted to [xq,∞)\text{deque} = \text{envelope of the inserted lines, restricted to } [x_q, \infty)

    Invariant. After each operation the deque holds, by decreasing slope, the lines of the envelope of everything inserted that are lowest somewhere on [xq,∞)[x_q, \infty), where xqx_q 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 xqx_q, which no later query visits.

  4. O(n+q) in total, amortized O(1) per operationO(n + q) \text{ in total, amortized } O(1) \text{ per operation}

    Cost. Every line is pushed once and popped at most once, from one end or the other, so nn insertions and qq 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 ℓk(x)\ell_k(x) first decrease and then increase (the breakpoints are sorted), so binary search finds the lowest line in O(log⁡n)O(\log n):

python
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 + b

O(log⁡n)O(\log n) per 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 O(1)O(1) front pops, at O(qlog⁡q)O(q \log q) for the sort.

Li Chao trees: lines in any order

When lines arrive in arbitrary slope order and queries in arbitrary xx order, the deque breaks down. If the query points are integers in a known range [0,C)[0, C), or can be compressed to one, a Li Chao tree needs no order at all. It is a segment tree over the xx 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 xx: walk from the root to the leaf containing xx and return the lowest of the stored lines at xx.

DerivationProof
  1. u(x)≤d(x)for all x∈[l,r) on the side d does not enteru(x) \le d(x) \quad \text{for all } x \in [l, r) \text{ on the side } d \text{ does not enter}

    Induct on insertions. Before an insertion the invariant holds. Follow the new line down: at node vv with range [l,r)[l, r) and midpoint mid\text{mid}, the winner uu at mid\text{mid} stays and the loser dd continues. For points xx of vv's range on the side not entered by dd, the two lines' difference has the same sign at xx as at the midpoint (they cross at most once, and on that side not at all):

  2. min⁡path(x)=min⁡all lines∀x\min_{\text{path}(x)} = \min_{\text{all lines}} \quad \forall x

    So every path through that side keeps a line (uu) at least as low as the discarded dd, and paths through the other side receive dd further down, by induction. The minimum along every path is the minimum over all lines.

  3. Tinsert=Tquery=O(log⁡C),#nodes≤nT_{\text{insert}} = T_{\text{query}} = O(\log C), \qquad \#\text{nodes} \le n

    Each step of an insertion or a query goes one level down a tree of depth ⌈log⁡2C⌉\lceil \log_2 C \rceil, and an insertion creates at most one new node, the empty one where it stops:

python
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 best

Tested against a brute-force minimum over random lines and query points. Nodes are created lazily, so a range of 10910^9 costs about 30 levels and only O(n)O(n) memory. The proof never used that the functions are lines, only that two of them cross at most once: parabolas (x−c)2+d(x - c)^2 + d with the same leading coefficient work too.

Check your understanding

A Li Chao node covers x∈[0,16)x \in [0, 16), with midpoint 8. Its stored line is lower at x=8x = 8, but the new line is lower at x=0x = 0. What happens to the new line?

  1. It replaces the stored line, since it is lower somewhere
  2. It is sent to the left child, [0,8)[0, 8)
  3. It is sent to the right child, [8,16)[8, 16)
  4. It is discarded, since it lost at the midpoint
Show the answer

B. It is sent to the left child, [0,8)[0, 8)

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 [x1,x2)[x_1, x_2), split the range into the O(log⁡C)O(\log C) canonical nodes of the segment tree and run a line insertion from each: O(log⁡2C)O(\log^2 C) 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: O(log⁡n)O(\log n) amortized per insertion and O(log⁡n)O(\log n) per query. Many team notebooks carry it as a "line container".

Lower bounds and the frontier

DerivationProof: tangent lines of a parabola
  1. ℓi(x)=−2ai x+ai2\ell_i(x) = -2a_i\,x + a_i^2

    Given distinct numbers a1,…,ana_1, \dots, a_n, take the tangent lines of the concave parabola y=−x2y = -x^2 at x=aix = a_i:

  2. ℓi(ai)=−ai2<ℓk(ai)(k≠i)\ell_i(a_i) = -a_i^2 < \ell_k(a_i) \quad (k \ne i)

    A tangent of a concave function lies above it and touches it only at its point, so at x=aix = a_i the line ℓi\ell_i is strictly lower than every other tangent:

  3. envelope order=sorted order of a1,…,an\text{envelope order} = \text{sorted order of } a_1, \dots, a_n

    So every line is essential, and the envelope lists them by decreasing slope −2ai-2a_i, that is, by increasing aia_i. 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 O(log⁡2n)O(\log^2 n) time per update, and Brodal and Jacob (2002) reached O(log⁡n)O(\log n) amortized per update with O(log⁡n)O(\log n) extreme-point queries, which in the dual are exactly "lowest line at xx" 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 nn segments can have Θ(n α(n))\Theta(n\,\alpha(n)) pieces, where α\alpha is the inverse Ackermann function, by the theory of Davenport–Schinzel sequences, and Hershberger (1989) computed it in O(nlog⁡n)O(n \log n) 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 (m,b)(m, b).
  • The monotone hull pops a middle line exactly when x13≤x12x_{13} \le x_{12}, since x13x_{13} is a weighted average of x12x_{12} and x23x_{23}; every line is pushed and popped once, so nn insertions and qq queries cost O(n+q)O(n + q).
  • Without sorted queries, binary search over the hull costs O(log⁡n)O(\log n) per query; without sorted slopes either, a Li Chao tree costs O(log⁡C)O(\log C) per operation, because two lines cross at most once.
  • Building an envelope of arbitrary lines sorts, so Ω(nlog⁡n)\Omega(n \log n) 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.

Question 1

Reading each line y=mjx+bjy = m_j x + b_j as the point (mj,bj)(m_j, b_j), which points correspond to the essential lines of the lower envelope?

  1. The vertices of the lower convex hull of the points
  2. The vertices of the upper convex hull of the points
  3. The points with the smallest intercepts bjb_j
  4. All of the points
Show the answer

A. The vertices of the lower convex hull of the points

ℓj(x)=⟨(mj,bj),(x,1)⟩\ell_j(x) = \langle (m_j, b_j), (x, 1)\rangle, so the lowest line at xx minimizes a linear function over the points, which happens at a hull vertex; the direction (x,1)(x, 1) points upward, so the minimizing vertex lies on the lower hull.

Question 2

The monotone convex hull trick processes nn insertions (slopes decreasing) and qq queries (xx increasing). What is the total running time?

  1. O(nq)O(nq)
  2. O((n+q)log⁡n)O((n + q)\log n)
  3. O(n+q)O(n + q)
  4. O(nlog⁡n+q)O(n \log n + q)
Show the answer

C. O(n+q)O(n + q)

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 nn and the work is O(n+q)O(n + q).

Question 3

Query points are integers in [0,109)[0, 10^9), and lines arrive in arbitrary order of slope. What does a Li Chao tree cost for nn insertions and qq queries?

  1. O((n+q)log⁡109)O((n + q)\log 10^9) time, about 30 steps per operation, and O(n)O(n) nodes
  2. O(n+q)O(n + q) time
  3. O(109)O(10^9) memory for the tree
  4. O(nq)O(nq) time, since each query checks every line
Show the answer

A. O((n+q)log⁡109)O((n + q)\log 10^9) time, about 30 steps per operation, and O(n)O(n) nodes

Each operation walks one root-to-leaf path of depth ⌈log⁡2109⌉=30\lceil \log_2 10^9 \rceil = 30, and nodes are created only when a line stops in an empty one, at most one per insertion.

Question 4

Why can no algorithm in the algebraic decision tree model build the lower envelope of nn arbitrary lines in o(nlog⁡n)o(n \log n) time?

  1. Because the envelope can have Θ(n2)\Theta(n^2) pieces
  2. Because the tangent lines of a parabola at a1,…,ana_1, \dots, a_n are all essential and appear in sorted order of the aia_i, so building the envelope sorts
  3. Because computing each crossing point needs a division
  4. It can: the monotone hull builds any envelope in O(n)O(n)
Show the answer

B. Because the tangent lines of a parabola at a1,…,ana_1, \dots, a_n are all essential and appear in sorted order of the aia_i, so building the envelope sorts

Sorting nn numbers reduces to building an envelope, so the envelope inherits sorting's Ω(nlog⁡n)\Omega(n \log n) 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".