Merge overlapping 2D line segments
Applied IntuitionSoftware Engineer · Technical ScreenLast updated
This problem tests your ability to handle geometric data by sorting and merging 1D intervals that exist within a 2D space, specifically focusing on collinear segments.
Problem Statement
You are given a list of line segments in a 2D plane. Each segment is defined by two endpoints (x1, y1) and (x2, y2). Two segments are considered "mergeable" if they are collinear and overlap or touch.
Your task is to write a function that takes a list of segments and returns a new list of segments where all overlapping or touching collinear segments have been merged into the longest possible continuous segments.
Function Signature
def merge_segments(segments: List[List[Tuple[float, float]]]) -> List[List[Tuple[float, float]]]
Constraints
- Each input segment is defined as
[(x1, y1), (x2, y2)]. - You may assume segments are not degenerate (i.e.,
x1 != x2ory1 != y2). - Coordinates are floating-point numbers.
Example 1
Input: [[(0, 0), (2, 2)], [(1, 1), (3, 3)], [(5, 0), (6, 0)]]
Output: [[(0, 0), (3, 3)], [(5, 0), (6, 0)]]
Explanation: The first two segments share the same slope and intersect, so they merge. The third is separate.
Example 2
Input: [[(0, 0), (1, 0)], [(2, 0), (3, 0)]]
Output: [[(0, 0), (1, 0)], [(2, 0), (3, 0)]]
Explanation: These are collinear but do not touch or overlap, so they remain separate.
Edge Cases
- Vertical segments (where
x1 == x2). - Segments provided in reverse order (e.g.,
[(2, 2), (0, 0)]). - A single point or single segment input.
Hints
Hint 1
Normalize each segment first so that the point with the smaller x-coordinate (or smaller y-coordinate if x is equal) comes first.
Hint 2
Group segments by their slope and their y-intercept (or x-intercept for vertical lines) to identify collinearity.
Hint 3
For each group of collinear segments, treat the problem as a 1D interval merging task by projecting the coordinates onto the primary axis of the line.
Follow-up questions
- How would you handle precision issues when comparing slopes for floating-point coordinates?
- What is the time complexity of your solution, and can you optimize the grouping process?
- How would you adapt this algorithm if the input included rays or infinite lines instead of finite segments?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.