You are given a collection of 2D line segments. Each segment may be represented either as:
-
two endpoints
(x1, y1)
and
(x2, y2)
, or
-
a polyline with multiple points, where
all points are guaranteed to be collinear
(so the polyline still lies on a single infinite line).
Two segments are mergeable if:
-
They lie on the
same infinite line
(collinear), and
-
Their projections on that line
overlap or touch
(i.e., they intersect or share an endpoint).
Task
Merge all mergeable segments and output the resulting set of maximal segments (no two output segments should be further mergeable).
Notes / edge cases
-
Handle
vertical lines
correctly (slope is infinite).
-
Avoid floating-point precision issues when grouping by line if possible.
-
Segments may be given with endpoints in any order.
Input/Output
-
Input: list of segments/polylines with integer coordinates.
-
Output: list of merged segments, each as two endpoints
(xa, ya)
and
(xb, yb)
.
Constraints
-
Up to ~10^5 segments.
-
Coordinates fit in 32-bit signed integers.