Skip to the workspace
Pebellslearn by building
Computational Geometry  ›  Lesson

The Sweep Line

Sweep Line 34 minA vertical line sweeps left to right across every segment's endpoints; an ordered active set tracks which segments the sweep is currently crossing, so only NEIGHBOURS in that order ever need an intersection test, not every pair

dsa / The Sweep Line

Explore each scene at your own pace.

01 · Three avenues, three cross streets

Three avenues, three cross streets

The Sweep Line

Definition
A sweep line is a technique that moves an imaginary vertical line across the plane, keeping an ordered set of the segments it currently touches, so that crossings are found by testing only neighbouring segments rather than every pair.
In plain words
Slide a ruler slowly across a map from left to right. At each moment only the roads under the ruler matter, lined up from top to bottom, and two roads can only cross if they are next to each other in that line.

In short: to find a crossing among many segments, you don't have to check every pair. Sweep a vertical line left to right. At any moment, the line is only crossing some subset of the segments — the active set — and that set has a real order: top to bottom, by where each segment currently sits. Keep the active set sorted (section 14's balanced structures do this with an O(log n) insert; a sorted list with bisect is fine here) and test a newly-inserted segment against only its two neighbours in that order. Anything farther away has a neighbour sitting between them that would have to cross first. The tested-pair count stays far below n², because every insertion costs at most two tests, however many segments are already active.

A vertical line partway across a city grid, with three horizontal avenues and one vertical street it currently crosses, the street's insertion point on a side panel showing it slotting in between the two avenues immediately above and below it, with only those two getting a tested badge and the far avenue greyed out

Three avenues, three cross streets

Meridian has three horizontal avenues and three north-south cross streets. Does any cross street actually meet an avenue?

step through it
1import bisect
2 
3def orientation(a, b, c):
4 cross = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
5 if cross > 0:
6 return 1
7 if cross < 0:
8 return -1
9 return 0
10 
11def on_segment(p, a, b):
12 return (min(a[0], b[0]) <= p[0] <= max(a[0], b[0]) and
13 min(a[1], b[1]) <= p[1] <= max(a[1], b[1]))
14 
15def segments_intersect(p1, p2, p3, p4):
16 d1 = orientation(p3, p4, p1)
17 d2 = orientation(p3, p4, p2)
18 d3 = orientation(p1, p2, p3)
19 d4 = orientation(p1, p2, p4)
20 if d1 != d2 and d3 != d4:
21 return True
22 if d1 == 0 and on_segment(p1, p3, p4):
23 return True
24 if d2 == 0 and on_segment(p2, p3, p4):
25 return True
26 if d3 == 0 and on_segment(p3, p1, p2):
27 return True
28 if d4 == 0 and on_segment(p4, p1, p2):
29 return True
30 return False
31 
32def seg_y_at(seg, x):
33 (x1, y1), (x2, y2) = seg
34 if x1 == x2:
35 return y1
36 t = (x - x1) / (x2 - x1)
37 return y1 + t * (y2 - y1)
38 
39def events_for(segments):
40 events = []
41 for i, (p, q) in enumerate(segments):
42 if p[0] > q[0]:
43 p, q = q, p
44 events.append((p[0], 0, i))
45 events.append((q[0], 1, i))
46 events.sort()
47 return events
48 
49def any_intersection(segments):
50 events = events_for(segments)
51 order = []
52 for x, kind_rank, idx in events:
53 if kind_rank == 0:
54 key = seg_y_at(segments[idx], x)
55 ys = [seg_y_at(segments[j], x) for j in order]
56 pos = bisect.bisect_left(ys, key)
57 order.insert(pos, idx)
58 for j in (order[pos - 1] if pos > 0 else None,
59 order[pos + 1] if pos < len(order) - 1 else None):
60 if j is not None and segments_intersect(*segments[idx], *segments[j]):
61 return True
62 else:
63 if idx in order:
64 order.pop(order.index(idx))
65 return False
66 
67routes = [
68 ((0, 0), (10, 0)), ((0, 2), (10, 2)), ((0, 4), (10, 4)), # three avenues
69 ((1, 5), (1, -1)), ((5, 5), (5, -1)), ((9, 5), (9, -1)), # three cross streets
70]
71print(any_intersection(routes))

The three avenues all start at x = 0 and go into the active set together, ordered by their y-values: [0, 2, 4]. The first cross street starts at x = 1 and inserts itself between the avenue at y=4 and... nothing above it, so it's tested only against its immediate neighbour, not all three avenues. That single test already finds a crossing, and the sweep returns True immediately — it never even reaches the other two cross streets.

Scene 1 of 6
Project context and further resources
You're building a piece ofMeridian — service areas & coverage
This piece — any_intersection(): Sweeps a line across a whole batch of routes to flag any crossing, without testing every pair.
Scenario A whole batch of new routes needs a single yes/no: does ANY pair of them cross? With dozens of routes, testing every pair gets expensive fast — Meridian needs an answer that doesn't grow like n squared.
any_intersection.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
any_intersection(segments) → boolTrue if any two of the segments cross or overlap, found by sweeping an ordered active set instead of checking every pair.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.