CComputer Science, Built

Act IV · Algorithms

Part 22 of 61

Geometry

Degreestarts at this level48 min of film17 chaptersprerequisites: Part 4, Part 16, Part 18, Part 20

How can a program that only computes signs of determinants get geometry right?

The part opens with one orientation test asked three ways in double precision and answered three ways: left, on the line, right. Kettner's grid of neighbouring doubles shows a speckled band of wrong signs, and the part repairs the predicate with a certified floating filter and an exact fallback before it builds anything. On that one primitive it builds convex hulls, with the lower bound that a hull of points on a parabola sorts, the sweep line for segment intersections, and Fisk's three-colour proof that a gallery of n walls needs at most n/3 guards. Fortune's beach line of parabolas draws the Voronoi diagram, Lawson's flips reach its dual, the Delaunay triangulation, and the lifting map shows that triangulation to be the shadow of a convex hull on a paraboloid. Backwards analysis prices random insertion, Seidel's planar linear programming and Welzl's enclosing circle. The part ends with range search, point location, the failure of kd-trees in high dimensions and graph indexes that replace them, duality, a robot among Minkowski sums, and the 3SUM barrier.

What you need. Coordinates, determinants of small matrices, and the equations of a line, a circle and a parabola.

Mathematics, ideas and history
robust predicates, convex hulls, sweep lines, Voronoi and Delaunay, the lifting map, kd-trees, the art gallery
What we build or compute
Fortune's sweep; Delaunay on the paraboloid

What you will be able to do

Degree

  • Compute an orientation test as a signed area and use it to run Graham's scan by hand.
  • Explain with an example why a floating-point orientation sign can be wrong, and what a filtered predicate does about it.
  • Prove the art gallery bound from a triangulation and a three-colouring.

Graduate

  • Prove the n log n lower bound for convex hulls by lifting numbers to a parabola, and state what Chan's algorithm gains when the hull is small.
  • Derive the in-circle test from the lifting map, and explain why Lawson's flips terminate.
  • Use backwards analysis to bound the expected work of random insertion and of Seidel's linear programming.

Research

  • State the 3SUM conjecture with its computational model, and reduce 3SUM to finding three collinear points.
  • Describe what is proved and what is only measured about graph indexes for nearest neighbours, and reproduce a published hard instance.

Industry

  • Choose between a kd-tree, an exact scan and an approximate graph index from the dimension and the data, and report recall with the number of distance evaluations.
  • Check a planned motion against obstacles over the whole segment, not at sampled points, and state the contact convention.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Degree 20 min · Graduate 44 min · Research 48 min · Industry 26 min.

  1. 0Left, right, or on the line?Degree2 min
  2. 1The one primitiveDegree3 min
  3. 2Convex hullsDegree4 min
  4. 3The sweep lineDegree2 min
  5. 4Guarding an art galleryDegree2 min
  6. 5Voronoi diagramsGraduate3 min
  7. 6Delaunay triangulationsGraduate3 min
  8. 7The lifting mapGraduate2 min
  9. 8Random order and backwards analysisGraduate3 min
  10. 9Linear programming in the planeGraduate3 min
  11. 10Range searchingDegree3 min
  12. 11Point locationGraduate2 min
  13. 12High dimensionsIndustry2 min
  14. 13Duality and the ham sandwichGraduate2 min
  15. 14Moving a robotIndustry3 min
  16. 15Frontier: exactness, 3SUM and nearest neighboursResearch4 min
  17. Recap, problems, and where this comes backAll tracks3 min

Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.

Lecture

The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.

Left, right, or on the line?Degree2 min

Here is the most basic question in computational geometry. Is the point p to the left of the line through q and r, or to the right, or on it? Take q at twelve, twelve and r at twenty-four, twenty-four, and put p a whisker from the point one half, one half, a few floating-point steps off the line. The test is a two by two determinant, and the answer should not depend on which point we list first. In double precision it does. Ask it one way and p is on the left. Rotate the three points and p is exactly on the line. Rotate again and p is on the right. The true answer is right, every time. This is not a rare accident: near this line, thousands of the nearest floating-point points get contradictory answers, and algorithms built on contradictory answers crash, loop forever, or return hulls that are not convex.

Kettner and colleagues illustrated this problem in 2008. Our grid starts at one half, one half. Each coordinate takes two hundred and fifty-six successive representable values toward positive infinity. Blue means floating-point left, green right, and grey collinear. The exact line is the diagonal. Rounded arithmetic produces a speckled band instead of one clean split. Red marks the answers that disagree with exact rational signs. These are all sixty-five thousand five hundred and thirty-six sampled grid points, not every float in a geometric neighborhood. We will repair the predicate before building geometric structures.

1The one primitiveDegree3 min

Almost every algorithm in this part asks one question, over and over. Walk from p to q; is r on your left? The answer is the sign of a two by two determinant built from the differences of the coordinates. The determinant is twice the signed area of the triangle p q r: positive when the three points turn counter-clockwise, negative when they turn clockwise, and zero when they lie on one line. Convex hulls, sweeps, triangulations and point-in-polygon tests are all built from this sign. Its cousin, the in-circle test, asks whether a point lies inside the circle through three others; it is a three by three determinant, and we will meet it with Delaunay.

Why does it fail? The determinant is a difference of two products, a minus b. For finite normal operations, rounding to the nearest double gives a small relative-error bound; underflow and overflow need separate handling. Near a line, a and b are almost equal, and their difference is tiny: smaller than the rounding errors made computing them. The sign of the result is then noise. But the error can be bounded. Jonathan Shewchuk proved that it is at most about three epsilon times the sizes of a and b. Within those arithmetic assumptions, a computed magnitude strictly exceeding the bound certifies the sign. When it isn't, ignoring the problem is dangerous: Kettner's paper shows the textbook incremental hull losing points, looping, and returning a polygon that is not convex.

Here is why the arithmetic domain matters. The stored binary64 number x approximates ten to the minus two hundred. These represented coordinates form a genuine counter-clockwise triangle: the exact determinant is x squared, which is positive. Its floating product underflows to zero. A rounded zero and a zero error estimate do not prove that the exact sign is zero. Our filter routes this case to rational arithmetic and returns positive. Overflow also takes that route. The diagram enlarges the coordinates so we can see the geometry.

A filtered predicate can combine speed with an exact sign. First compute the determinant in floating point. Trust it only when the operations remain finite and normal and its magnitude strictly exceeds the certified error bound. Underflow, overflow and ambiguous signs take the exact route. Shewchuk uses expansions of doubles; our teaching fallback uses rational arithmetic on the original represented inputs. The table records twenty thousand seeded tests of each kind, including raw timing repetitions and exact reference signs. Fallback share and speed depend on these inputs and this implementation. Filtering saves exact work when the floating result is certified; exactness is not universally free. Integer hulls and incremental triangulations use Python's unbounded integers. Fortune's sweep, linear programming and robot planning still use floating constructions, so an exact predicate alone does not make every later coordinate exact.

2Convex hullsDegree4 min

The convex hull of a set of points is the smallest convex polygon that contains them all: stretch a rubber band around nails and let go. Ronald Graham's scan, from 1972, starts at the lowest point, sorts the others by the angle they make with it, and walks through them in that order, keeping the hull so far on a stack. Each new point is pushed; but first, while the last two points on the stack and the new one turn clockwise, the last point cannot be on the hull, and is popped. Every point is pushed once and popped at most once, so after sorting the walk is linear. Graham needed it at Bell Labs, for a plotter drawing ten thousand points.

These counters compare five teaching implementations on seeded point sets. The square and disk have small hulls. The rounded circle has many hull vertices, but rounding means some generated points are not extreme. The table reports the actual h. Jarvis wraps one vertex per round and checks the points again. The largest circle run is left unmeasured, shown by a dash; it is not replaced with an invented count. Graham and Andrew's monotone chain sort before scanning. Here we add orientation or determinant evaluations and sorting-comparator calls, including a determinant used inside a comparison in both named counters. This is a chosen work metric, not elapsed CPU time. Quickhull counts its farthest-point determinants too and divides around farthest points; its worst case is quadratic even when some random cases are cheap. Chan's bound depends on output size. Our groups use sorting hulls and binary tangents, and the measured constants belong to this implementation and these inputs. No universal library winner follows from this table.

Could a cleverer algorithm avoid the n log n? No, and the proof is a reduction. Suppose you want to sort some numbers. Lift each number x to the point x, x squared. All the lifted points lie on a parabola, which is convex, so every one of them is a vertex of the hull. Walk around the hull from the leftmost point and you meet them in sorted order. So any hull algorithm is also a sorting algorithm, with linear extra work. Part 16 proved that sorting by comparisons needs n log n; Michael Ben-Or extended the bound in 1983 to algorithms that compute with arithmetic and test signs, which is what hull algorithms do.

There is a loophole. The lower bound needs every point on the hull. When the hull has only h vertices, can we pay n log h? Timothy Chan's algorithm splits the points into groups of m and finds each group's hull with a sorting method; our instrument uses the monotone chain. Then it wraps the whole set like Jarvis: to find the next vertex, it asks each small hull for its tangent from the current point, which a binary search answers in log m steps. If m equals h, that is h rounds of n over m times log m, and n log h in all. We don't know h, so Chan guesses: m equal to four, then sixteen, then two hundred and fifty-six, squaring each time, and abandons a guess after m rounds. The failed guesses form a geometric series and cost nothing extra in order. Kirkpatrick and Seidel reached n log h first, in 1986, under the title The ultimate planar convex hull algorithm. Chan's 1996 paper also gives an output-sensitive algorithm in three dimensions; the general n log n construction is not the only bound.

3The sweep lineDegree2 min

Given n line segments, which pairs cross? Testing every pair takes n squared tests, even when almost nothing crosses. Jon Bentley and Thomas Ottmann, in 1979, swept a vertical line across the plane from left to right. It stops only at events: the endpoints of segments, and crossings, once they have been predicted. Along the way it keeps the status: the segments the line currently meets, ordered from top to bottom. The key observation is that two segments can only cross after they become neighbours in that order, so we only ever test neighbours: when a segment arrives, against the two beside it; when one leaves, the two it separated; and at a crossing, the two that swap places meet new neighbours. Watch the line move. Each crossing is found by a test made when its two segments first became adjacent, and at the crossing they trade places in the status. With a balanced tree for the status and a heap for the events, the cost is n plus k, times log n, for k crossings.

We ran our sweep on short random segments, from a hundred to three thousand. Every output pair was independently checked against all pairs after timing. On these general-position inputs, each endpoint and crossing supplies an event; neighbour tests are far fewer than all pairs. These are counts of executed tests, not a bound on total runtime. The textbook balanced-tree algorithm takes n plus k times log n. Our teaching implementation uses a plain list with linear updates, so its measured runtime does not inherit that bound. Chazelle and Edelsbrunner's 1992 algorithm achieves n log n plus k in its comparison model. The broader idea is a sweep: turn a two-dimensional question into a sequence of one-dimensional ones. Fortune's sweep will do that for Voronoi diagrams. Related sweeps support map overlay, chip design checks and polygon operations; robust production versions also need explicit degeneracy handling.

4Guarding an art galleryDegree2 min

Klee's gallery is a simple polygon without holes. A point guard sees along every segment that stays inside it. Chvátal proved in 1975 that floor n over three guards always suffice, and some polygons require that many. This comb has seventeen walls and five separated teeth. No guard can see all the way into two tips, so it needs five guards, exactly the bound. The theorem concerns continuous point guards; camera direction, range and obstacles inside a room would define other problems.

Steve Fisk found a proof in 1978 that fits on a postcard. First triangulate the gallery with diagonals. That is always possible: Gary Meisters showed every polygon has an ear, three consecutive corners whose triangle lies inside, and cutting ears one by one triangulates it. The triangles, joined across diagonals, form a tree. Colour the corners of one triangle blue, green and yellow; each neighbouring triangle shares two coloured corners, so its third has only one colour left. Walking the tree colours every corner, and every triangle gets all three colours. Some colour is used at most n over three times. Put a guard on every corner of that colour. Each triangle has one, and a triangle is seen entirely from any of its corners, so the whole gallery is watched.

How fast can we triangulate a simple polygon without holes? Maintaining a set of valid ears gives a quadratic algorithm. Our short implementation repeatedly rescans candidates and containment points, and can take cubic time. The displayed count records candidate and containment tests, not every arithmetic operation. Splitting into monotone pieces, then using stacks, gives n log n time. Chazelle proved a linear-time bound in 1991. Our two hundred polygons, each with sixty vertices, all pass independent triangle, area and colouring checks. The smallest colour gives a valid guard set, usually smaller than the worst-case bound, without certifying a minimum. Finding a minimum continuous point-guard set is existential-real complete, hence NP-hard. This is a different task from Fisk's constructive guarantee. Coverage and triangulation motivate practical variants, whose geometric and visibility assumptions must be stated separately.

5Voronoi diagramsGraduate3 min

Scatter n distinct sites over the plane. Which site is nearest to each point? The Voronoi regions answer that question. A shared edge lies on two sites' perpendicular bisector. In general position, a vertex is the centre of an empty circle through three sites. Cocircular and collinear inputs need separate conventions. For at least three noncollinear sites, Euler gives at most two n minus five finite vertices and three n minus six edges. Dirichlet and Voronoi studied this partition. Nearest-pump regions also offer a geometric interpretation of Snow's cholera investigation; the historical map itself is not a computed Voronoi diagram.

Steven Fortune found, in 1986, a way to build the diagram with a sweep. The difficulty is that a line sweeping down meets a Voronoi region before it meets the region's site, so it cannot know yet what lies below. Fortune's answer: consider the points that are as close to a site above the line as to the line itself. For each site, they form a parabola. The lowest of these parabolas form the beach line. Any point above it is closer to some site than to the sweep line, so no site still below the line can claim it: above the beach line, the diagram is final. As the line moves, the breakpoints where arcs meet slide along Voronoi edges and draw them. When the line reaches a site, a new arc is born, a thin spike that widens. When an arc shrinks to nothing between its neighbours, three sites are equally far from one point and from the line: that point is a Voronoi vertex, and the line touches the bottom of the empty circle through the three sites. Those are the only two events, so with a balanced tree for the beach line the sweep takes n log n.

Our finite-precision sweep keeps the beach line in a plain list. We ran it on seeded random sites up to two thousand. On these nondegenerate inputs, circle events match two n minus two minus h, with h hull sites. Cancelled event predictions count as false alarms. Every output triangle set agrees with a separate Qhull construction after timing. This is full numerical agreement on these inputs, not an exact-arithmetic proof for all inputs. The list implementation can take quadratic time. The balanced-tree Fortune algorithm has the n log n bound under its event and arithmetic assumptions.

6Delaunay triangulationsGraduate3 min

Connect the sites with triangles. There are many ways; which is best? Boris Delaunay's answer, from 1934: join three sites whenever the circle through them has no other site inside. Those circles are exactly the empty circles of the Voronoi vertices, so the Delaunay triangulation is the Voronoi diagram's dual: an edge for every pair of neighbouring regions. Whether a point lies inside a circle through three others is decided by a sign, the in-circle test, a three by three determinant with squared distances in its last column. Like the orientation test, it can be made exact.

How do we find it? Charles Lawson's method, from 1977, starts from any triangulation at all. This one connects the points as a sweep from left to right meets them, and it is full of slivers: its thinnest angle is under half a degree. Look at two triangles sharing an edge. If the far corner of one lies inside the circle of the other, the edge is illegal; flip it, replacing it with the other diagonal of the quadrilateral. Repeat. Seventeen flips later no edge is illegal, and what is left is the Delaunay triangulation. Its smallest angle has grown tenfold, and Robin Sibson proved that among all triangulations of the points, Delaunay's maximizes the smallest angle. Why does flipping ever stop? The next chapter will show that each flip pushes down a surface in three dimensions, which cannot go down forever.

The empty-circle property has useful consequences. Delaunay refinement adds sites to improve simulation meshes. Ruppert's quality and termination guarantees require assumptions about the input geometry; a small required input angle cannot simply be erased. Terrain triangulations and natural-neighbour interpolation use related constructions. In general position, nearest-neighbour edges and the Euclidean minimum spanning tree lie in the Delaunay graph. We check spanning-tree weights next. Sweeps, divide and conquer, and randomized insertion with suitable point location achieve n log n bounds in their arithmetic models. Our walking locator is a simpler implementation and does not acquire that guarantee merely by shuffling.

Here are seventy points, their Delaunay edges, and a minimum spanning tree. Every green edge is present in the triangulation. Remove an MST edge a b and consider its cut. Any site inside the disk with diameter a b is closer to both ends. Joining that site to the endpoint on the other side gives a shorter crossing edge, contradicting minimality. Thus the diameter disk is empty and the edge is Delaunay. Kruskal can search the linear-sized Delaunay graph. For every displayed size, including eight thousand points, we independently run complete-graph Prim after timing and compare total weights within a declared numerical tolerance. Equal weights certify these numerical results; they need not identify a unique tree when ties occur. The two timing columns are separate host measurements.

7The lifting mapGraduate2 min

Here is the most beautiful fact in this part. Take the Delaunay triangulation of some points, seen from above. Now lift every point straight up, onto the paraboloid z equals x squared plus y squared. The lifted points sit on a convex bowl, so all of them are on the three-dimensional convex hull. Look at the hull from below: its faces are triangles. Why those triangles? Take a circle in the plane. Its points, lifted, all lie on one plane, because on the circle x squared plus y squared is a linear function of x and y. A point inside the circle lifts to below that plane, and a point outside lifts to above it. So a circle through three sites is empty exactly when every other lifted point is above the plane through those three: exactly when the three lifted points form a face of the lower hull. The Delaunay triangulation is the shadow of the lower convex hull of the lifted points. Kevin Brown saw it in 1979, and it holds in every dimension: Delaunay in d dimensions is a hull in d plus one.

The lifting map explains the in-circle test. Put four lifted coordinates in the determinant. For counter-clockwise a, b, c, a positive sign means d lifts below their plane and lies inside their circle. Reversing that orientation reverses the sign. In this integer example both determinants are ninety-six; subtracting d's row and expanding the last column proves the identity exactly. A strict illegal-edge flip lowers the lifted surface. With finitely many triangulations and consistent handling of cocircular ties, such flips terminate. The upper envelope of tangent planes gives the same nearest-site regions: squared distance is the common x squared plus y squared minus the tangent-plane height. Our finite Qhull lower hull and Delaunay triangle sets agree on this sample. That numerical check illustrates the theorem; it does not replace an exact construction or a degeneracy policy.

8Random order and backwards analysisGraduate3 min

The simplest way to build a Delaunay triangulation is to add the points one at a time. Here is a triangulation, and a new point to insert. First find the triangle that contains it. Then find every triangle whose empty circle the new point spoils, the triangles in conflict with it. Remove them all, leaving a hole shaped like a star around the new point, and join the new point to every corner of the hole. The number of new triangles is the new point's degree. Lawson's flips, starting from the triangle that contains the point, carry out exactly this change one edge at a time. The question is what the whole sequence of insertions costs.

An adversarial insertion order can require quadratic update work. Random order gives an expected bound, not a guarantee for every shuffle. Condition on the i sites present. The last inserted site is uniform among them. Its expected final degree is twice the number of edges divided by i. Euler bounds that below six for a nondegenerate planar triangulation with at least three vertices. This controls the final insertion star and leads to an expected linear update history. Our implementation also counts destroyed triangles, flip intermediates and artificial outer vertices; its counter is not this final degree and has no asserted strict nine n plus one bound. Suitable conflict lists give expected n log n point location. Our simpler triangle walk is measured separately and has no such proven bound here. Seidel called this backwards analysis: condition on the set, then randomize which object came last. We will use the same idea for linear programming.

These tables count all triangle objects created by this implementation, including intermediate and artificial ones. On the sampled random sets and random orders, that count stays roughly proportional to n. It is not a measurement of the final degree below six. The adversarial set combines a shallow convex chain with points inserted above its middle. Its chosen order produces quadratic growth in the displayed counts. Shuffling that same set sharply reduces this run's work. The expected update bound concerns randomness in the order for a fixed admissible set; a single successful shuffle is an illustration, not a worst-case runtime proof for our walking implementation.

9Linear programming in the planeGraduate3 min

A linear program asks for the point of a convex region that goes furthest in a given direction. In the plane the region is an intersection of half-planes, and the direction is a vector c. Part 23 builds the simplex method for thousands of dimensions; in two, Raimund Seidel's algorithm from 1991 fits in a dozen lines. Add the constraints one at a time, in random order, keeping the optimum of those seen so far. If the current optimum satisfies the new constraint, nothing changes. If it violates it, the new optimum must lie on the new constraint's line, and finding it there is a one-dimensional problem: intersect the line with the earlier constraints, an interval, and take the better end. Watch: of nine constraints, only three move the optimum.

What does backwards analysis prove? In the exact bounded model, with a consistent tie rule and feasible prefixes, at most two input constraints form a basis for the optimum. Some basis constraints can instead come from the fixed box. The last constraint is uniform among i inputs, so the probability it changes the chosen optimum is at most two over i. A change costs order i, giving expected linear work. This expectation is over insertion order. Our floating implementation uses explicit tolerances and a finite box. For every trial at every size, a separate SciPy linear program checks feasibility and objective after timing. The table reports average moves, counted one-dimensional work, and the exact harmonic bound. Agreement on these instances does not turn floating tolerances into an exact theorem. The factorial dependence on dimension makes this approach useful chiefly for fixed small dimension.

Backwards analysis also finds the smallest enclosing circle. Add points in random order. A point outside the current minimum circle must lie on the new minimum circle. Recurse with that point fixed on the boundary, then with two fixed points. A minimum circle has a basis of at most three points, so the probability of a top-level rebuild at step i is at most three over i. Three H n is an expected upper bound, not a prediction for one random order. The table reports actual top-level rebuilds and single-run host times. Post-timing checks establish containment and a numerical minimality certificate: the centre is a convex combination of two or three boundary support points. Containment alone would not certify a minimum. Welzl's exact-model algorithm has expected linear work. Floating circle construction here is numerical; small cases also receive independent reference checks. Megiddo gave deterministic linear algorithms in fixed dimension.

10Range searchingDegree3 min

A database of shops, each with a position, is asked for every shop in a rectangle on the map. Checking every shop is linear; we want the answer in time close to its size. Jon Bentley's kd-tree, from 1975, splits the points at their median x, then each half at its median y, then each quarter at its median x again, alternating, until every cell holds one point. It takes n log n to build and linear space. To answer a query, descend from the root into every cell that meets the rectangle, and report the points inside. Here the query visits forty-six of the hundred and nineteen nodes. Why is that cheap? A vertical line crosses only the cells along one path in every two levels, about the square root of n of them, so the query costs root n for the rectangle's boundary plus the k points reported. Bentley invented it as an undergraduate at Stanford.

A closed rectangle has a boundary, and that boundary matters. Query x equal to one and y between zero and one, including both endpoints. There are three records on this line, because two records share one position. Median partitioning can put equal split coordinates in either child. When the lower query bound equals the split, skipping the left child can lose a valid record. Visit it too. The executed query returns records zero, one and two. Geometry includes the boundary; the implementation must preserve that convention.

For each size up to three hundred thousand seeded random points, we checked all forty closed-rectangle queries against a full NumPy scan after timing. The table reports mean output size and node visits. These samples fall below root n plus k, but big O does not promise a leading constant of one. Node visits do not directly measure latency, and the last column times construction only. A balanced kd-tree's standard orthogonal-reporting bound in fixed dimension is n to the one minus one over d, plus output size. Ties need consistent closed-boundary handling, as the previous witness showed. The dimension dependence warns us that pruning may deteriorate as dimension grows.

If we can afford more space, queries get faster. A range tree is a balanced tree on x in which every node also keeps its points sorted by y. It uses n log n space and answers in log squared n plus k. Bernard Chazelle and Leonidas Guibas removed a log with fractional cascading: each sorted list keeps pointers into its children's lists, so a single binary search at the root serves the whole path down. Interval trees and segment trees answer the other common question, which stored intervals contain a given point. Databases use R-trees, which pack nearby rectangles into the pages of a B-tree; they sit under PostGIS, SQLite's spatial index and most map servers.

11Point locationGraduate2 min

Your phone knows its coordinates; which country, which county, which time zone is it in? A map is a subdivision of the plane by n segments, and point location asks which face holds a query point. The first fast answer, by David Dobkin and Richard Lipton in 1976, draws a vertical line through every endpoint. Inside one slab no two segments cross, so they are sorted from bottom to top. A query is two binary searches: one for the slab, one for the segment just below the point. That is log n time. The trouble is space: a long segment crosses many slabs, and can be stored in every one, n squared in the worst case.

Stop each vertical wall at the nearest segment or box boundary. We assume disjoint segments, distinct endpoint x coordinates, and no vertical segments. That partitions the box into trapezoids. Our seven-segment example has twenty-two. Charge left boundaries to endpoints: a left endpoint contributes at most two, a right endpoint at most one, plus the box. Hence at most three n plus one; these separated samples attain equality. A different algorithm inserts segments randomly and records splits in a search DAG. Our illustration directly enumerates walls and counts cells; it does not execute that search structure or benchmark queries. The randomized structure has expected linear space and logarithmic query cost under its stated query and general-position model, with expected n log n construction. Backwards analysis proves those bounds. Kirkpatrick's triangulation hierarchy provides a deterministic alternative for planar point location.

12High dimensionsIndustry2 min

Nearest-neighbour queries also arise for high-dimensional embeddings. Here are distances from one seeded query to two thousand uniform unit-cube points. The farthest-to-nearest ratio approaches one as dimension grows in these samples. On a separate twenty-thousand-point sample, we counted the kd-tree nodes visited for exact nearest-neighbour queries and checked each answer against a full distance scan. By twenty-four dimensions this run visits the entire tree. This is a warning about pruning and data distribution, not a universal lower bound on all high-dimensional indexes. Approximation and additional structure lead to other tradeoffs.

Approximate search admits several designs; locality-sensitive hashing is one. Here we illustrate a graph approach. Link points to nearby neighbours, preserving links in diverse directions. A query explores links toward better candidates with a bounded search beam. Malkov and Yashunin's HNSW adds sparse upper layers. This small drawing is a schematic of that navigation, not the recorded traversal of our twenty-thousand-point index. Our teaching graph uses clustered sixteen-dimensional data; the actual layer counts appear on screen. Production libraries use related ideas with different details. This sampled performance does not supply a worst-case guarantee; published work already exhibits hard inputs for popular graph rules.

We checked all one thousand true neighbour positions across a hundred held-out queries using full distance scans. A brute-force query evaluates twenty thousand distances. The single-layer nearest-link graph and the layered diverse-link graph use the beam widths shown. Their recall and distance counts are averages over the same queries. Recall at ten is the fraction of each query's ten true neighbours recovered, averaged across queries. Our diverse-link graph does better on these clustered samples. Counts include executed query distance evaluations, with repeated evaluations counted; they exclude index construction, memory traffic and elapsed latency. This is not a benchmark against LSH or a production library. FAISS, pgvector, Milvus and Lucene implement related vector-search methods. Their measured performance must be evaluated in their own versions and deployment conditions.

13Duality and the ham sandwichGraduate2 min

Map a point a, b to the line y equals a x minus b. Each coloured point becomes a line of the same colour. A nonvertical line y equals m x plus c maps to the point m, minus c. Incidence is preserved: two primal points on a line become two dual lines meeting at its dual point. Check the inequality carefully. If b is greater than m a plus c, then a m minus b is less than minus c. A point above a primal line therefore becomes a dual line below its dual point. This convention reverses the above relation; the algebra fixes the direction.

An arrangement partitions the plane with lines. With no parallels and no triple intersections, n lines give n choose two plus n plus one faces. Degeneracies reduce that count. The zone theorem bounds the total boundary complexity of faces crossed by another line by order n, supporting quadratic construction. Collinearity becomes concurrency under our duality. An arrangement algorithm that explicitly handles degeneracies can therefore detect three collinear distinct input points. Three-sum reductions explain conditional barriers to a truly subquadratic algorithm in stated models. They are not an unconditional quadratic lower bound, and logarithmic improvements are possible. Duality also links convex hulls, half-plane intersections and envelopes. Each transformation needs its incidence and sign conventions checked.

One more theorem with a sandwich in its name. Scatter red points and blue points. Is there a single line that cuts both sets in half? Always. Arthur Stone and John Tukey proved in 1942 that in d dimensions one hyperplane halves any d sets: bread, ham and cheese in three. Here nine red and nine blue points, and a line with four of each on either side and one of each on it. We found it by trying lines through a red and a blue point; Lo, Matoušek and Steiger find it in linear time, by dualizing the points to lines and pruning. Halving cuts like this are how geometric divide-and-conquer splits its work evenly.

14Moving a robotIndustry3 min

Our triangular robot slides without turning. This model permits contact with obstacle boundaries and forbids interior overlap. Replace each convex obstacle by its Minkowski sum with the reflected robot. The triangle's reference point can then represent the entire translated robot. Its forbidden region is the interior of these configuration obstacles. The example uses disjoint convex obstacles. A shortest route can bend at their vertices, so join mutually visible vertices with collision-free segments. Overlapping obstacles would require the vertices of their union, including new boundary intersections, which this simple builder does not construct. Dijkstra finds the shortest path in this visibility graph. Every path edge is checked independently; the animated triangle follows the resulting route with boundary contact allowed.

Collision checking must test a complete motion segment. Consider the diagonal from minus one hundred to one hundred against the unit square. Probes at one quarter, one half and three quarters all miss the strict interior: the middle probe lands exactly on a corner. Yet the segment crosses the obstacle between parameters one half and point five zero five. The enlarged view shows the two corner crossings and the interior between them. Our convex half-plane clipping checks the full parameter interval. This planner allows contact with obstacle boundaries; its path and tree edges are independently checked against exact rational interval calculations.

Explicit visibility graphs become difficult in large configuration spaces. An RRT samples a point, finds the nearest tree node, and accepts a short collision-free step toward the sample. Our nearest-node search is a linear scan. This seeded tree reaches the goal after the displayed number of nodes. All parent edges, including branches off the final path, pass independent segment checks. Its path is longer than the visibility optimum in green. All twenty tested seeds find a path in this scene, with the displayed mean length ratio. RRT star has asymptotic optimality under its sampling, clearance and connection assumptions. Sampling avoids explicitly constructing every obstacle boundary, but still depends on the geometry of collision checking and the chosen configuration metric.

This panel considers broader motion-planning models. A planar rigid body that can translate and rotate has configuration coordinates x, y and theta. A robot arm adds joint coordinates. Reif's 1979 hardness result concerns general motion planning with multiple moving parts in the input; it does not make this fixed translating-triangle example PSPACE-hard. For semi-algebraic input descriptions, Canny's 1988 roadmap method has singly exponential dependence on configuration dimension, with further dependence on description size and polynomial degrees. This is a theoretical algorithm overview, beyond the simple planner we executed. Sampling planners choose a configuration metric, a sampling rule and a collision oracle. Their completeness or optimality guarantees require the corresponding clearance and connection assumptions. Collision predicates, simulation meshes and bounding-volume hierarchies connect these ideas to other applications; the later graphics part develops the ray-tracing example.

15Frontier: exactness, 3SUM and nearest neighboursResearch4 min

Robustness requires more than one exact determinant. Exact predicates support correct combinatorial decisions when the algorithm's invariants, constructions and degeneracy conventions are also correct. Our underflow witness showed why a filter must certify its arithmetic conditions. The displayed rational-to-float timing ratio comes from this Python implementation on these near-collinear inputs. It is not a universal price of exactness. Raw repetitions and matching outputs are retained. Adaptive filters use a cheap certified case and fall back when necessary. Our fallback uses Python rationals; Shewchuk's expansion arithmetic is a different implementation. Symbolic perturbation consistently selects a combinatorial convention for degenerate inputs. It does not repair already-rounded constructed coordinates. Intersections can increase coordinate complexity, especially through repeated constructions. Exact constructions, interval methods and snap-rounding techniques make different precision and topology tradeoffs. We do not infer a general three-dimensional impossibility or open problem from this example.

Three-sum asks whether three distinct input positions sum to zero. We use distinct numerical values for this geometric reduction. Sorting and two pointers give a quadratic algorithm in the arithmetic model. Map each value a to a, a cubed. For distinct a, b and c, the collinearity determinant factors into pairwise differences times a plus b plus c. Our fourteen values are distinct, so the factorization applies. Exhaustively checking all triples finds the same two zero sums and two collinear triples. Gajentaan and Overmars developed reductions connecting three-sum to families of geometric decision problems. Those are conditional hardness relationships. The cited 2014 and 2018 real-RAM results improve logarithmic factors. A conjecture excluding n to the two minus epsilon algorithms requires a specified model and number domain; it is not a proved lower bound or a statement about every restricted integer instance.

Approximate near-neighbour theory needs a precise problem. Exact-search lower bounds depend on dimension, metric, storage and the cell-probe model; they do not prohibit every small fast index on structured data. For the randomized Euclidean near-neighbour task at a chosen radius, with constant success probability and approximation c greater than one, data-independent hashing has an exponent approaching one over c squared under its standard asymptotic assumptions. Andoni and Razenshteyn's 2015 data-dependent scheme attains rho equal to one over two c squared minus one, with dimension and space factors shown here. Its optimality comparison concerns a hashing model, not every possible index. Indyk and Xu's 2023 paper already gives hard instances for HNSW, NSG and fast-preprocessing DiskANN. The paper also proves low-intrinsic-dimension guarantees for slow-preprocessing DiskANN, a distinct construction. An algorithm name alone does not transfer a theorem between those variants.

Here are three research exercises with a dated starting point. For three-sum, write down the computational model before claiming a conditional barrier. For planar point-line incidences, Chan and Zheng in 2022 obtained an n to the four thirds counting algorithm, removing an extra iterated-logarithm factor from earlier bounds. Model-specific lower bounds do not prove unrestricted optimality. For graph search, published hard instances already exist. Reproduce one, specify the construction and query rules, then test what a proposed change actually guarantees. The starred exercise follows that last route. It is a reproducible research extension, not a claim that nobody has constructed a bad input.

Recap, problems, and where this comes backAll tracks3 min

We built exact integer predicates and a floating orientation filter with a rational fallback. We compared five convex-hull implementations with explicit counters, swept intersections, and proved a guard bound. Voronoi, Delaunay and lifting linked planar diagrams to three-dimensional hulls. Random order explained expected update costs and low-dimensional linear programming. Range queries, point location and approximate neighbour graphs showed different storage and query tradeoffs. Finally, a translating robot used configuration obstacles and independently checked collision-free segments. Every measurement belongs to its stated input, arithmetic and implementation model.

Where this comes back. Part 23 takes linear programming to many dimensions with the simplex method. Part 27 builds fine-grained complexity on three-sum. Part 47's search engine adds vector search over embeddings, with the graphs of chapter twelve, and Part 48 serves nearest-neighbour queries on maps. Part 51 draws triangles with the orientation test, which graphics calls an edge function, and traces rays through bounding-volume hierarchies. And Part 52 returns to floating point and computing with real numbers.

These ideas recur in geographic overlay, mesh generation, graphics, robotics and vector search. Production systems choose different robustness policies, indexes and precision models. PostGIS, GEOS and S2 are not interchangeable implementations. CGAL and Triangle offer geometry algorithms with documented contracts. Sampling planners still require collision checking. Vector-search libraries offer graph and other index families. Our teaching implementations illustrate the primitives; they do not reproduce every library or establish production performance.

The notes contain six worked exercises. The build exercise asks you to implement a bounded-integer hull in Pebble and verify it on the emulator; this chapter does not claim that port has already run. The starred exercise starts from a published graph hard instance, then asks you to state and test a specific modification. Pause to choose an exercise and record the input and arithmetic assumptions before implementing it.

Next time, optimization. Many problems are a choice of the best point of a polytope. The simplex method walks the polytope's edges; duality certifies the answer from the other side. When integrality makes a problem hard, relaxations and random hyperplanes still get provably close, and online, without seeing the future, you can still be competitive. Part 23, Optimization.

The books and papers this part follows are on screen and in the notes. Thank you for watching.

Where it goes next. Part 23 takes linear programming to many dimensions with the simplex method; Part 27 builds fine-grained complexity on 3SUM; Part 47's search engine and Part 48's maps use the neighbour graphs of chapter 12; Part 51 draws triangles with the orientation test and traces rays through bounding-volume hierarchies; Part 52 returns to floating point.

Key results

The part's results in one place, for revision.

Orientation\(\displaystyle \operatorname{orient}(p,q,r)=\operatorname{sign}\bigl[(q_x-p_x)(r_y-p_y)-(q_y-p_y)(r_x-p_x)\bigr]\)
Hulls sort\(\displaystyle x\mapsto(x,x^2):\ \text{the }\allowbreak \text{hull }\allowbreak \text{lists }\allowbreak \text{the } x_i \text{ in }\allowbreak \text{order}\ \Rightarrow\ \Omega(n\log n)\)
Art gallery\(\displaystyle \lfloor n/3\rfloor\ \text{guards }\allowbreak \text{always }\allowbreak \text{suffice, }\allowbreak \text{and }\allowbreak \text{are }\allowbreak \text{sometimes }\allowbreak \text{necessary}\)
The lifting map\(\displaystyle (x,y)\mapsto(x,y,x^2+y^2):\quad\allowbreak \text{Delaunay}=\text{shadow }\allowbreak \text{of }\allowbreak \text{the }\allowbreak \text{lower }\allowbreak \text{convex }\allowbreak \text{hull}\)
Backwards analysis\(\displaystyle \Pr[\text{step } i \text{ moves }\allowbreak \text{the }\allowbreak \text{optimum}]\le\frac2i\ \Rightarrow\ \mathbb E[\text{moves}]\le 2H_n\)
3SUM as collinearity\(\displaystyle \det\begin{pmatrix}1&a&a^3\\1&b&b^3\\1&c&c^3\end{pmatrix}=(b-a)(c-a)(c-b)(a+b+c)\)

Try it

Lab 22 · One predicate, and the shadow of a hull

Ask the orientation test on a grid of neighbouring doubles and compare every sign with exact arithmetic; build a Delaunay triangulation by random insertion with exact integer predicates and check it against the lower hull of the points lifted to a paraboloid; then count how often Seidel's planar LP moves its optimum.

Figure produced by Lab 22: One predicate, and the shadow of a hull
Produced by the lab below, seed 0, in 0.5 s.
python -m videos.cs.labs 22 needs numpy, scipy, matplotlib · download lab22.py · source on GitHub
orientation on 128 x 128 neighbouring doubles  5,346 of 16,384 floating signs wrong (33%)
filtered predicate                             0 wrong; exact fallback on 100% of grid points, 0% of random points
hull of 400 points                             15 vertices, 1,574 orientation tests and 2,945 sort comparisons
Delaunay, random insertion                     783 triangles = 2n - 2 - h; equal to the lifted lower hull
mean degree of a site                          5.91   (Euler: below 6)
Seidel's LP, 200 constraints                   optimum moved 9.3 times on average over 200 orders   (2 H_n = 11.8)

Near a line the floating determinant's sign is noise, and a filter with an exact fallback repairs it; with exact predicates the triangulation built by flips is the lifted hull's shadow, triangle for triangle.
The code (106 lines; it asserts its own result)
"""Lab 22: catch floating point giving wrong orientation signs, then check Delaunay against the lifted hull."""

from videos.coursekit import labs  # noqa: I001  (must stay first: it lets explainer.cs import without manim)

import numpy as np

from explainer.cs.algo import geometry as geo

TITLE = "One predicate, and the shadow of a hull"
GOAL = ("Ask the orientation test on a grid of neighbouring doubles and compare every sign with exact arithmetic; "
        "build a Delaunay triangulation by random insertion with exact integer predicates and check it against the "
        "lower hull of the points lifted to a paraboloid; then count how often Seidel's planar LP moves its optimum.")
TASKS = [
    "Move q and r to (2, 2) and (3, 3) in the grid experiment. How does the number of wrong signs change, and why does the size of the coordinates matter?",
    "Insert the Delaunay points in sorted order (order=sorted(range(n), key=pts.__getitem__)) and compare D.created with the random order.",
    "Sort 200 random integers by lifting each x to (x, x*x) and walking geo.monotone_chain's hull: check that the walk is the sorted order.",
]


def run(seed=0):
    rng = np.random.default_rng(seed)
    lab = labs.Lab()

    # 1. Kettner's grid: 128 x 128 successive doubles from (1/2, 1/2), against the line through (12, 12), (24, 24)
    q, r, size = (12.0, 12.0), (24.0, 24.0), 128
    fl, ex = geo.kettner_grid((0.5, 0.5), q, r, size)
    wrong = int((fl != ex).sum())
    assert (ex == np.sign(np.arange(size)[:, None] - np.arange(size)[None, :])).all(), "the exact sign is the diagonal"
    assert wrong > 0.1 * fl.size, "rounding gets a large share of these signs wrong"
    xs = 0.5 + np.arange(size) * 2.0 ** -53
    exact_runs = 0
    for _ in range(2000):
        i, j = (int(v) for v in rng.integers(0, size, 2))
        sign, used_exact = geo.orient_adaptive((xs[i], xs[j]), q, r)
        assert sign == ex[j, i], "the filtered predicate always returns the exact sign"
        exact_runs += used_exact
    far = [geo.orient_adaptive(tuple(rng.uniform(-1, 1, 2)), q, r)[1] for _ in range(2000)]
    assert not any(far), "far from the line the floating filter certifies its own answer"
    lab.row("orientation on 128 x 128 neighbouring doubles", f"{wrong:,} of {fl.size:,} floating signs wrong ({wrong / fl.size:.0%})")
    lab.row("filtered predicate", f"0 wrong; exact fallback on {exact_runs / 2000:.0%} of grid points, {np.mean(far):.0%} of random points")

    # 2. hulls: the monotone chain against scipy, and the hull of a parabola as a sorting network
    from scipy.spatial import ConvexHull

    pts = list(dict.fromkeys((int(a), int(b)) for a, b in rng.integers(0, 10_000, (400, 2))))
    n = len(pts)
    ctr = geo.Counter()
    hull = geo.monotone_chain(pts, ctr)
    assert set(hull) == {pts[i] for i in ConvexHull(np.array(pts)).vertices}, "the same hull vertices as Qhull"
    values = [int(v) for v in rng.choice(10_000, 200, replace=False)]
    lifted = geo.monotone_chain([(x, x * x) for x in values])
    start = lifted.index(min(lifted))
    assert [p[0] for p in lifted[start:] + lifted[:start]] == sorted(values), "a hull algorithm sorts"
    lab.row(f"hull of {n} points", f"{len(hull)} vertices, {ctr.n:,} orientation tests and {ctr.cmp:,} sort comparisons")

    # 3. Delaunay by random insertion (exact integer predicates) against the lifting map
    D = geo.delaunay(pts, seed=seed)
    tris = D.triangles()
    assert tris == geo.lifting_delaunay(pts), "Delaunay = the lower hull of (x, y, x^2 + y^2)"
    assert len(tris) == 2 * n - 2 - len(hull), "Euler: 2n - 2 - h triangles"
    for a, b, c in tris[:60]:  # the empty-circle property, exactly, on a sample
        A, B, C = pts[a], pts[b], pts[c]
        if geo.orient_int(A, B, C) < 0:
            B, C = C, B
        assert all(geo.incircle_exact(A, B, C, pts[d]) <= 0 for d in rng.integers(0, n, 40)), "an empty circle"
    edges = 3 * n - 3 - len(hull)
    lab.row("Delaunay, random insertion", f"{len(tris)} triangles = 2n - 2 - h; equal to the lifted lower hull")
    lab.row("mean degree of a site", f"{2 * edges / n:.2f}   (Euler: below 6)")
    assert 2 * edges / n < 6

    # 4. Seidel's LP: the optimum moves at most 2 H_n times in expectation
    m, orders = 200, 200
    theta = rng.uniform(0, 2 * np.pi, m)
    H = [(float(np.cos(t)), float(np.sin(t)), 1.0) for t in theta]  # half-planes tangent to the unit circle
    c = (0.6, 0.8)
    moves = [geo.seidel_lp(H, c, seed=s)[1] for s in range(orders)]
    x = geo.seidel_lp(H, c, seed=seed)[0]
    from scipy.optimize import linprog

    ref = linprog([-c[0], -c[1]], A_ub=[h[:2] for h in H], b_ub=[h[2] for h in H], bounds=[(None, None)] * 2)
    assert abs(c[0] * x[0] + c[1] * x[1] + ref.fun) < 1e-6, "the same optimum as scipy's LP"
    harmonic = 2 * sum(1 / i for i in range(1, m + 1))
    assert 3 < np.mean(moves) < harmonic + 0.5, "backwards analysis: at most 2 H_n moves in expectation"
    lab.row("Seidel's LP, 200 constraints", f"optimum moved {np.mean(moves):.1f} times on average over {orders} orders   (2 H_n = {harmonic:.1f})")
    lab.note = ("Near a line the floating determinant's sign is noise, and a filter with an exact fallback repairs it; "
                "with exact predicates the triangulation built by flips is the lifted hull's shadow, triangle for "
                "triangle.")

    fig, ax = labs.figure(2, size=(11, 4.8))
    from matplotlib.colors import ListedColormap

    shown = np.where(fl != ex, 3, fl + 1)  # 0 right, 1 on the line, 2 left, 3 wrong
    ax[0].imshow(shown, origin="lower", interpolation="nearest", vmin=0, vmax=3,
                 cmap=ListedColormap([labs.GREEN, labs.GREY, labs.BLUE, labs.RED]))
    ax[0].grid(False)
    ax[0].set(title="Floating orientation near (1/2, 1/2): red is a wrong sign",
              xlabel="x: doubles after 1/2   (blue: left, green: right, grey: on the line)", ylabel="y: doubles after 1/2")
    P = np.array(pts)
    ax[1].triplot(P[:, 0], P[:, 1], tris, color=labs.BLUE, lw=0.6)
    H2 = np.array(hull + hull[:1])
    ax[1].plot(H2[:, 0], H2[:, 1], color=labs.GOLD, lw=1.6)
    ax[1].plot(P[:, 0], P[:, 1], ".", color=labs.INK, ms=3)
    ax[1].set(title=f"Delaunay triangulation of {n} integer points (gold: the hull)", xlabel="x", ylabel="y",
              aspect="equal")
    lab.fig = fig
    return lab

Now change it

  1. Move q and r to (2, 2) and (3, 3) in the grid experiment. How does the number of wrong signs change, and why does the size of the coordinates matter?
  2. Insert the Delaunay points in sorted order (order=sorted(range(n), key=pts.__getitem__)) and compare D.created with the random order.
  3. Sort 200 random integers by lifting each x to (x, x*x) and walking geo.monotone_chain's hull: check that the walk is the sorted order.

Problems, with solutions

Try each problem before opening its solution.

  1. Graham's scan after sorting. Use distinct points, an extreme pivot and a consistent radial tie rule. Prove fewer than 2n orientation tests in the scan.

    Solution

    Each executed test either pops one stack element or ends that point's inner loop. Every point is pushed once and popped at most once; at most n−1 tests pop, and at most n−1 tests end a loop. Thus at most 2n−2 tests occur. For the sequence (0,0),(3,0),(1,1),(3,3),(0,3) in angular order, (1,1) is popped when (3,3) arrives. The stack's convex-chain invariant, with the chosen collinear policy, proves correctness. Sorting and its comparator calls are excluded from this linear scan bound; integer products must be promoted before use.

  2. Trapezoids. In a fixed box, let n disjoint nonvertical segments have distinct endpoint x coordinates, with endpoints strictly inside. Show at most 3n+1 cells when vertical walls stop at the nearest segment or box boundary.

    Solution

    Charge each cell to the endpoint defining its left boundary; charge the cell touching the box's left side to the box. A left endpoint defines at most two cells to its right, a right endpoint at most one. Hence 2n+n+1. Under these strict assumptions all contributions occur: n=0 gives one, and a single internal segment gives four. Shared endpoints and crossings require new counting conventions. This is a size proof, not a construction-time proof.

  3. Lifting and sign. Let a,b,c be noncollinear and counter-clockwise. Derive the circle/lower-plane equivalence and in-circle determinant.

    Solution

    A circle with centre (u,v) and radius r satisfies x²+y²=2ux+2vy+r²−u²−v². Its lift lies in the plane z=2ux+2vy+k. A point is inside exactly when its lifted height is below that plane. In the 4×4 determinant with rows (x,y,x²+y²,1), subtract d's row from each other row and expand the last column. Column operations remove the linear terms in d, leaving rows (x−d_x,y−d_y,|p−d|²). For a=(0,0), b=(4,0), c=(0,4), d=(1,1), the determinant is 96>0. Reversing a,b reverses the sign; cocircularity gives zero and needs a consistent tie policy.

  4. Seidel's expectation. Work in exact arithmetic with a fixed bounding box, feasible prefixes and a consistent unique-optimum/tie convention. Show at most 2H_n expected changes and O(n) expected work.

    Solution

    Condition on the unordered i constraints present. A basis of at most two input constraints fixes the chosen optimum; fixed box sides may supply part of the basis. Removing a constraint outside that basis cannot change the chosen optimum. The last input is uniform among i constraints, so the change probability is at most 2/i. Linearity of expectation gives Σ2/i=2H_n, and Σ(2/i)O(i)+O(n)=O(n). It is an upper bound over order, not an equality prediction. Floating tolerance, infeasibility and unboundedness need explicit handling; SciPy agreement on finite samples is a separate check.

  5. Build a bounded-integer hull in Pebble. Implement orientation and monotone chain, using integer coordinates 0≤x,y<2^15, then test on the emulator.

    Solution

    Store two coordinate arrays; mergesort lexicographically and discard duplicate pairs. Build a lower stack, popping while the last two points and the new point have orientation ≤0; append the new point. Repeat on reversed order for the upper stack. Concatenate both without repeated endpoints. Empty and singleton inputs return themselves; a collinear non-singleton set returns its two extreme endpoints. Each difference has magnitude at most 32767; each product is at most 32767²=1,073,676,289 in magnitude. Their difference is at most 2,147,352,578, below signed-32-bit maximum 2,147,483,647. Merely saying coordinates are “below 2^15” would not give a lower bound or this safety proof. Verify empty, duplicate, collinear, square and extreme-bound fixtures before 10,000 points; compare vertex set and CCW order with the Python reference. Count actual emulator instructions separately from comparator calls. This episode supplies the algorithm and arithmetic proof, not an executed Pebble port; the requested implementation is the exercise.

  6. ★ Reproduce, then extend a graph-search hard instance. Start with Indyk–Xu (2023), rather than claiming that bad HNSW inputs are unknown.

    Solution

    First specify the exact graph construction, pruning, beam, entry point, distance, tie rule, random seed and query distribution. Reproduce one published difficult family, checking true neighbours by a full independent scan. Report mean recall@10 over held-out queries and the actual query distance evaluations at increasing n. Count repeated evaluations; exclude and separately report build work. Linear-looking finite data alone do not prove Ω(n). For an extension, change one rule and either prove a bound with explicit assumptions or produce a counterexample to a precise proposed claim. A slow-preprocessing DiskANN theorem cannot be transferred to a teaching HNSW implementation by name. This is a reproducible research protocol, not a supplied novel theorem or a claim that the extension has been executed.

Notes and sources

Glossary

方向测试 orientation test · 内圆测试 in-circle test · 谓词 predicate · 自适应精确谓词 adaptive exact predicate · 误差界 error bound · 凸包 convex hull · 礼品包装 gift wrapping · 单调链 monotone chain · 输出敏感 output-sensitive · 扫描线 sweep line · 事件队列 event queue · 状态结构 status structure · 美术馆问题 art gallery problem · 耳朵 ear · 三着色 three-colouring · Voronoi 图 Voronoi diagram · 海滩线 beach line · 点事件 site event · 圆事件 circle event · Delaunay 三角剖分 Delaunay triangulation · 空圆性质 empty-circle property · 边翻转 edge flip · 提升映射 lifting map · 下凸包 lower hull · 随机增量构造 randomized incremental construction · 反向分析 backwards analysis · 冲突 conflict · 半平面 half-plane · kd 树 kd-tree · 范围查询 range query · 分散层叠 fractional cascading · 点定位 point location · 梯形图 trapezoidal map · 维数灾难 curse of dimensionality · 可导航小世界图 navigable small world · 对偶 duality · 排列 arrangement · 火腿三明治定理 ham-sandwich theorem · 构形空间 configuration space · Minkowski 和 Minkowski sum · 可见性图 visibility graph · 3SUM 难 3SUM-hard

Sources

Canon. Books:

  • de Berg, Cheong, van Kreveld & Overmars, Computational Geometry: Algorithms and Applications (3rd ed., 2008);
  • Preparata & Shamos, Computational Geometry: An Introduction (1985);
  • O'Rourke, Computational Geometry in C (1998) and Art Gallery Theorems and Algorithms (1987);
  • Devadoss & O'Rourke, Discrete and Computational Geometry (2011);
  • Edelsbrunner, Geometry and Topology for Mesh Generation (2001);
  • LaValle, Planning Algorithms (2006).

Papers:

  • Hull and sweep algorithms: Graham (1972); Jarvis (1973); Andrew (1979); Bentley & Ottmann (1979); Kirkpatrick & Seidel, "The ultimate planar convex hull algorithm?" (1986); Chazelle & Edelsbrunner (1992); Chan, "Optimal output-sensitive convex hull algorithms in two and three dimensions" (1996).
  • Lower bounds: Ben-Or (1983).
  • Art galleries and triangulation: Chvátal (1975); Meisters (1975); Fisk (1978); Garey, Johnson, Preparata & Tarjan (1978); Lee & Lin (1986); Chazelle, "Triangulating a simple polygon in linear time" (1991); Abrahamsen, Adamaszek & Miltzow (2018).
  • Voronoi and Delaunay: Voronoi (1908); Delaunay (1934); Lawson (1977); Sibson (1978); Brown, "Voronoi diagrams from convex hulls" (1979); Guibas & Stolfi (1985); Edelsbrunner & Seidel (1986); Fortune, "A sweepline algorithm for Voronoi diagrams" (1987); Guibas, Knuth & Sharir (1992); Ruppert (1995).
  • Randomized algorithms: Clarkson & Shor (1989); Mulmuley (1990); Seidel, "Small-dimensional linear programming and convex hulls made easy" (1991) and "Backwards analysis of randomized geometric algorithms" (1993); Welzl (1991).
  • Linear programming and enclosing circles: Megiddo (1983, 1984); Welzl (1991).
  • Spanning trees: Shamos & Hoey, "Closest-point problems" (1975).
  • Range search and point location: Bentley, "Multidimensional binary search trees" (1975); Dobkin & Lipton (1976); Kirkpatrick (1983); Guttman, "R-trees" (1984); Chazelle & Guibas, "Fractional cascading" (1986).
  • Duality and arrangements: Stone & Tukey (1942); Lo, Matoušek & Steiger (1994).
  • Robustness and exact computation: Edelsbrunner & Mücke, "Simulation of simplicity" (1990); Shewchuk, "Adaptive precision floating-point arithmetic and fast robust geometric predicates" (1997); Yap, "Towards exact geometric computation" (1997); Hobby (1999); Kettner, Mehlhorn, Pion, Schirra & Yap, "Classroom examples of robustness problems in geometric computations" (2008).
  • Motion planning: Lozano-Pérez & Wesley (1979); Reif (1979); Canny (1988); Kavraki, Švestka, Latombe & Overmars (1996); LaValle (1998).
  • 3SUM: Gajentaan & Overmars, "On a class of O(n²) problems in computational geometry" (1995); Grønlund & Pettie (2014); Chan (2018).
  • Nearest neighbours: Indyk & Motwani (1998); Andoni & Indyk (2006); O'Donnell, Wu & Zhou (2014); Andoni & Razenshteyn (2015); Malkov & Yashunin, "Efficient and robust approximate nearest neighbor search using hierarchical navigable small world graphs" (2016, 2018); Indyk & Xu (2023).

Selected primary-source links:

  • Chan (1996): https://www.cs.jhu.edu/~misha/Spring20/Chan96.pdf
  • Andoni–Razenshteyn (2015): https://arxiv.org/abs/1501.01062
  • Chan–Zheng (2022): https://arxiv.org/abs/2111.03744
  • Indyk–Xu (2023): https://arxiv.org/abs/2310.19126
About this partfrom its README

Part 22 of the 61-part series. The syllabus connects geometry to optimization, databases, graphics and numerical computing. The central question is how a geometric algorithm's arithmetic, invariants and input conventions together justify its result.

The executed instrument is explainer/cs/algo/geometry.py; compute.py builds 17 schema-2 payloads. Raw timing repetitions, output checks and host/protocol metadata remain in the cache. Independent references run after the timed operation. Producer wall time includes setup and references and is not an algorithm benchmark. Tests live in tests/test_cs22_geometry.py.

What is computed and built
  1. Predicates. Integer orientation promotes NumPy scalars before products. Floating orientation has a conservative filter and a Python rational fallback for uncertain, underflowing or overflowing intermediate arithmetic. This is not Shewchuk's expansion implementation. The grid is the one-sided 256×256 grid of successive binary64 coordinates starting at (1/2,1/2). A separate executed witness uses stored binary64 x=fl(10^-200): x>0 and its exact square is positive, while the floating product rounds to zero.
  2. Hulls. Jarvis, Graham, monotone chain, quickhull and Chan, including exact angular ordering and collinear tangent ties. Operation totals count orientation/determinant evaluations and sort-comparator calls, including Quickhull farthest-point determinants. A comparator that calls orientation contributes both. Other arithmetic and tie comparisons are excluded. A dash for the largest circle/Jarvis case means unmeasured, not an estimate. Rounded circle inputs need not all be extreme. Chan's 1996 output-sensitive theorem covers 2D and 3D.
  3. Sweep. The event trace and all output pairs up to 3,000 segments are checked. The measured status is a list with linear updates. The balanced-tree O((n+k)log n) theorem describes a different implementation and arithmetic model.
  4. Gallery. Fisk's triangulation, three-colouring and smallest colour class guard a simple polygon without holes. All 200 sampled polygons receive area, triangulation and colouring checks. Maintained-ear algorithms are quadratic; our repeated candidate/containment rescans can be cubic. A guard certificate proves coverage, not a minimum number of guards.
  5. Voronoi. A moving beach line explains Fortune's construction. The finite list implementation agrees with Qhull on every measured sample after timing. General-position Euler counts and numerical agreement are stated separately from exact arithmetic and handling of degenerate inputs.
  6. Delaunay. Empty circles, strict Lawson flips and the CCW in-circle sign. Randomized integer insertion rejects duplicate and fractional inputs and uses a data-dependent artificial triangle. Exact local-circle, area and Euler certificates check the measured integer triangulations. Finite Qhull constructions elsewhere in the chapter remain numerical.
  7. Lifting. Lift (x,y) to (x,y,x²+y²). Empty circles become lower supporting planes; strict flips lower a surface with finitely many triangulations. The integer example gives matching 4×4 and 3×3 determinants of 96.
  8. Random insertion. The expected final degree is below six by Euler. Created-object counters include artificial and destroyed triangles and flip intermediates; they are not that final degree. There is no asserted strict 9n+1 bound for this counter. Conflict-list point location gives a textbook expected O(n log n) algorithm; our walking locator does not inherit it.
  9. LP and enclosing circles. Finite-box LP with explicit tolerances is checked by SciPy for every trial at every size. Harmonic bounds are exact sums. Circle certificates check containment and a boundary-support convex combination of the centre, which establishes numerical minimality.
  10. Range queries. Median-partition kd-trees and fully checked closed ranges. A duplicate-coordinate witness returns all three records on the split plane, including two at the same position. Query node visits and build time are different metrics; O(√n+k) does not promise a constant of one.
  11. Point location. Slabs and the 3n+1 trapezoid count assume disjoint nonvertical segments with distinct endpoint x coordinates in a box. Our drawing enumerates walls; it does not implement or time a randomized search DAG. The DAG's expected bounds belong to that separate algorithm.
  12. High dimensions. Seeded unit-cube distance concentration and kd-tree visits illustrate distribution-dependent pruning. Teaching NSW/HNSW-style graphs use clustered 16D data. All 1,000 true neighbour positions for 100 queries are checked. Mean recall@10 and query distance-evaluation counts exclude build work, memory traffic and latency. No LSH or production-library performance comparison is executed.
  13. Duality. (a,b) maps to y=ax−b; a nonvertical line y=mx+c maps to (m,−c). Incidence is preserved. A point above a primal line gives a dual line below its dual point, since b>ma+c implies am−b<−c. Arrangement counts require no parallels or triple intersections. The ham-sandwich example verifies its actual side counts.
  14. Planning. A translating triangle becomes a point among convex configuration obstacles. Boundary contact is allowed; strict interior collision is forbidden. A segment through two square corners demonstrates why fixed probes miss collisions. Full convex clipping is independently checked with rational interval references for path and every RRT parent edge. Vertex visibility assumes disjoint configuration obstacles; overlapping ones require union-boundary intersections that this builder does not construct. The 20-seed success result is a finite observation, not a universal guarantee. Broader roadmap theorems use semi-algebraic descriptions and include input-size and polynomial-degree factors. Sampling requires a metric and sampling rule.
  15. Research. Exact predicates alone do not repair bad constructions or invariants. The distinct-value cubic reduction illustrates conditional 3SUM hardness. Selected 2015 hashing exponents include their Euclidean task, dimension/space factors and model. Chan–Zheng (2022) give O(n^(4/3)) planar incidence counting. Indyk–Xu (2023) already give hard graph-search instances and separate low-intrinsic-dimension guarantees for slow-preprocessing DiskANN. These dated results do not assert present-day open status.

The Euclidean-MST experiment compares Delaunay/Kruskal total weights with full complete-graph Prim at every displayed size, including 8,000 points. Agreement uses an explicit numerical tolerance and need not imply a unique tree.

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. The primitive: orientation as a signed area; why rounding fails and Shewchuk's error bound; Kettner's grid computed (11,972 wrong signs of 65,536); adaptive predicates measured (exact stage needed 0% on random input, 70% on nearly collinear input; float wrong 3,713 times in 20,000 there).
  2. Convex hulls: Graham's scan animated; Jarvis, Graham, monotone chain, quickhull and Chan counting their work on 10,000 points in a square, a disk and on a circle; the Ω(n log n) lower bound by lifting to a parabola (proved); Chan's O(n log h) with binary-search tangents and squaring guesses; Kirkpatrick–Seidel.
  3. The sweep line: Bentley–Ottmann animated with its status and events; events exactly 2n + k, 19,812 pair tests against 4.5 million pairs at n = 3,000; Chazelle–Edelsbrunner.
  4. The art gallery theorem: Chvátal's comb; Fisk's three-colouring proof animated; ear clipping; random 60-gons (17.3 guards against the bound of 20); monotone pieces, Chazelle's linear time, NP- and ∃ℝ-hardness.
  5. Voronoi diagrams; Fortune's sweep animated with its beach line of parabolas; circle events exactly 2n − 2 − h, checked against the lifting map up to n = 2,000.
  6. Delaunay triangulations: the empty circle; duality with Voronoi; Lawson's flips animated (17 flips, smallest angle 0.48° to 4.81°, Sibson); the Euclidean MST inside the Delaunay edges (Shamos–Hoey), checked against Prim on 32 million pairs.
  7. The lifting map: a 3D tour of the paraboloid, the lower hull, and a circle lifting to a plane; the in-circle test as a 4 × 4 determinant; why Lawson's flips stop; the Voronoi diagram as an upper envelope; checked against scipy.
  8. Randomized incremental construction and backwards analysis: one insertion's conflicts; expected degree < 6 by Euler; 8.6–8.9 triangles per point in random order, 874,107 for 1,600 points in a bad order.
  9. Seidel's LP animated (the optimum moves three times in nine); Pr ≤ 2/i measured against 2H_n up to 10⁵; Megiddo; Welzl's smallest enclosing circle animated and measured.
  10. Range searching: a kd-tree built level by level; queries below √n + k up to 300,000 points; range trees, fractional cascading, interval and segment trees, R-trees.
  11. Point location: Dobkin–Lipton slabs; the trapezoidal map (3n + 1, hit on every random map); Mulmuley and Seidel's randomized search structure; Kirkpatrick.
  12. High dimensions: distance concentration measured to d = 1,000; a kd-tree visiting 100% of its nodes at d = 24; LSH (callback to Part 20); a navigable small world and HNSW built (99.7% recall for 182 distance computations against 20,000).
  13. Duality and arrangements; the zone theorem; a ham-sandwich cut (Stone–Tukey; Lo–Matoušek–Steiger).
  14. Motion planning: Minkowski sums and configuration space; the visibility graph and Dijkstra; an RRT grown in the same space (1.29× the optimum on average); Reif, Canny, sampling planners; BVHs (Part 51).
  15. Frontier: exact geometric computation and its price (124×); symbolic perturbation and snap rounding; 3SUM as collinearity of (a, a³), drawn and checked; Gajentaan–Overmars; LSH's optimal exponents, data-dependent hashing, Indyk–Xu on graph indexes; open problems (3SUM, Hopcroft's problem, guarantees for navigable graphs). Outro.

Computed: every number above, in videos/cs/cs22/compute.py with explainer/cs/algo/geometry.py (tested in tests/test_cs22_geometry.py): Kettner's grid and the adaptive filter's rates and costs; five hulls counting their work; Bentley–Ottmann against brute force; ear clipping and Fisk's colouring; Fortune's sweep; Delaunay three ways (incremental, Lawson, Fortune) against scipy's lifted hull; the EMST over Delaunay against Prim; Seidel's LP against scipy; Welzl; kd-tree visits; trapezoid counts; distance concentration, kd-trees against dimension, NSW and HNSW recall; a ham-sandwich cut; configuration spaces, the visibility graph and an RRT; 3SUM as collinearity. Visuals: the speckled grid of wrong signs; Graham's stack; the sweep's status; Fisk's three colours; Fortune's beach line drawing the diagram; Lawson's flips; the paraboloid in 3D; conflicts and the star-shaped hole; Seidel's optimum moving; kd-tree cells; trapezoids; HNSW's layers; points and dual lines; a robot sliding among grown obstacles, and a random tree exploring; the cubic of 3SUM. In practice: GIS and maps (PostGIS, S2), CAD and meshing (CGAL, Triangle), robot motion planning (OMPL), collision detection and rasterization in graphics, vector search (FAISS, pgvector). Reading: de Berg, Cheong, van Kreveld & Overmars, Computational Geometry: Algorithms and Applications; Preparata & Shamos; O'Rourke, Computational Geometry in C; Devadoss & O'Rourke, Discrete and Computational Geometry; Edelsbrunner, Geometry and Topology for Mesh Generation; LaValle, Planning Algorithms; Shewchuk 1997; Kettner et al. 2008; Fortune 1987; Seidel 1991, 1993; Chan 1996; Malkov & Yashunin 2016.

中文讲义

本讲的中文部分(与英文版对应)。

习题与解答
  1. 排序后的 Graham 扫描。 假设点互异、选取极端枢轴并一致处理同射线平局。 每次方向测试要么弹栈,要么结束当前内循环。每点只压入一次、至多弹出一次, 因此两类测试各至多 n−1 次,总数至多 2n−2。例中角序 (0,0),(3,0),(1,1),(3,3),(0,3),加入 (3,3) 时弹出 (1,1)。 凸链不变量证明正确性;排序与比较器调用不包含在扫描界中,整数乘法前须提升。

  2. 梯形计数。 框内互不相交的非竖直线段,端点严格在框内且横坐标互异。 把单元记到决定其左边界的端点上,最左单元记到框上。左端点至多贡献两个, 右端点至多一个,加框共至多 3n+1。严格假设下各项都出现:零线段为一格, 一条内部线段为四格。共享端点和交叉需要另立约定;空间计数不证明构建时间。

  3. 提升与符号。 a、b、c 不共线且逆时针。圆方程展开为 x²+y²=2ux+2vy+r²−u²−v²,所以圆提升后位于平面 z=2ux+2vy+k。 圆内等价于提升高度低于该平面。四阶行列式的前三行各减 d 行,再沿最后一列展开, 通过列运算消去 d 的线性项,得到行 (x−d_x,y−d_y,|p−d|²) 的三阶式。 a=(0,0)、b=(4,0)、c=(0,4)、d=(1,1) 时值为 96>0;交换 a、b 则变号。 共圆得到零,需要一致的平局处理。

  4. Seidel 的期望。 采用精确算术、固定边界框、可行前缀和一致的唯一最优解或平局规则。 固定当前 i 个约束集合,至多两个输入约束构成决定所选最优解的基,框边也可能参与。 删除基外约束不会改变所选解。最后输入在 i 个约束中均匀分布,改变概率至多 2/i。 故期望改变次数至多 Σ2/i=2H_n,期望工作为 Σ(2/i)O(i)+O(n)=O(n)。 这是顺序上的上界,不是单次预测。浮点容差、不可行与无界必须另行处理;样本 SciPy 核对是独立的数值检查。

  5. Pebble 有界整数凸包。 整数坐标须满足 0≤x,y<2^15。双数组存点,归并排序、去重, 用栈构造下链,非左转时弹出;逆序构造上链,拼接时去掉重复端点。空、单点原样返回, 共线集保留两极端点。差的绝对值至多 32767,乘积至多 1,073,676,289,两个乘积之差 的绝对值至多 2,147,352,578,小于有符号 32 位最大值 2,147,483,647。 只说“小于 2^15”没有给出下界,不能据此证明安全。先测空、重复、共线、正方形与极限坐标, 再测一万点;与 Python 参考核对顶点和逆时针顺序。模拟器指令数须实际测量。 本章提供算法与算术证明,并未执行 Pebble 移植;实现与验证是练习内容。

  6. ★ 复现再扩展图困难实例。 从 Indyk–Xu(2023)出发,已有坏例不能当成尚无人构造。 明确构图、剪枝、束宽、入口、距离、平局、种子和查询分布。复现一个发表的困难族, 用独立完整扫描求真邻居。随 n 增长报告留出查询的平均 recall@10 和实际查询距离计算数, 重复计算也计入;构建工作单独报告。有限数据看似线性并不证明 Ω(n)。扩展时只改一条规则, 对精确命题证明带假设的界或给出反例。慢速预处理 DiskANN 的定理不能凭名称移到教学 HNSW。 这里提供可复现协议,并不声称已经执行扩展或得到新定理。

Build the film

python -m videos.cs.cs22.compute        # the part's numbers, into .cache/cs22
python tools/build.py cs22                  # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs22 Hook   # one chapter, silent, with a contact sheet

Scenes: videos/cs/cs22. Setup: see the course page. Source of these notes: the README and the scenes' narration.

Build it
python -m videos.cs.cs22.compute
python -m unittest discover -s tests -p 'test_cs22_geometry.py' -v
python tools/build.py cs22 -q l
python tools/build.py cs22

Cached schema-2 data must be rebuilt with the corresponding instrument source; the cached-only entry rejects stale payloads. Source/preview evidence is tracked in docs/qa/computer-science-built-progress.md. Sampled silent previews and automated speech/cue checks do not complete continuous listening, Chinese speech, whole-video native review or runtime approval at the final narration pace.