Merge collinear overlapping 2D segments
You are given a collection of 2D line segments. Each segment can be represented by two endpoints (x1, y1) and (x2, y2), or by a polyline where all points are guaranteed to be collinear.
Two segments are considered mergeable if they lie on the same infinite line and their projections on that line overlap or touch (intersect or share an endpoint).
Your task is to merge all mergeable segments and output the resulting set of maximal segments, meaning no two output segments should be further mergeable.
Considerations:
- Handle vertical lines correctly.
- Avoid floating-point precision issues when grouping by line.
- Segment endpoints may be provided in any order.
Input: A list of segments/polylines with integer coordinates.
Output: A list of merged segments, each represented by two endpoints (xa, ya) and (xb, yb).
Constraints:
- Up to ~10^5 segments.
- Coordinates fit in 32-bit signed integers.
AI interview prep
Core dilemma
Efficiently identifying and merging collinear, overlapping line segments while managing geometric calculations and potential precision issues.
3 tradeoffs and 2 stress tests locked
Interview prep
Unlock the interviewer X-Ray rubric, tradeoff matrix, stress tests, clarifying questions, and key concepts.
Merge collinear overlapping 2D segments
You are given a collection of 2D line segments. Each segment can be represented by two endpoints (x1, y1) and (x2, y2), or by a polyline where all points are guaranteed to be collinear.
Two segments are considered mergeable if they lie on the same infinite line and their projections on that line overlap or touch (intersect or share an endpoint).
Your task is to merge all mergeable segments and output the resulting set of maximal segments, meaning no two output segments should be further mergeable.
Considerations:
- Handle vertical lines correctly.
- Avoid floating-point precision issues when grouping by line.
- Segment endpoints may be provided in any order.
Input: A list of segments/polylines with integer coordinates.
Output: A list of merged segments, each represented by two endpoints (xa, ya) and (xb, yb).
Constraints:
- Up to ~10^5 segments.
- Coordinates fit in 32-bit signed integers.