Fuse Collinear Point Chains Along Shared Lines
Greedy & IntervalsAuto-graded · 19 test casesLast updated
Group point lists by the infinite line they lie on, then fuse those that overlap or touch along that line, and return each fused group's unique points ordered along the line.
You are given a list of pieces. Each piece is a list of at least two 2D points [x, y]. Every point inside one piece lies on a single straight line, but the points may be listed in any order, and a piece may contain interior points as well as its two extreme points. A piece may be horizontal, vertical or diagonal.
The extent of a piece is the stretch of its line between its two extreme points.
Two pieces belong together if they lie on the same infinite line and their extents overlap or touch, which includes sharing just one endpoint. This relation is transitive. If A joins B and B joins C, then A, B and C form one group, even if A and C do not meet directly. Pieces that merely cross each other on different lines are never joined.
For every group, output the list of distinct points that occur in any piece of the group, ordered along the line from one end to the other. For a non-vertical line, order by increasing x. For a vertical line, order by increasing y.
Return one such list per group.
Rules for output order and format
- Groups are returned in order of the smallest original index among the pieces they contain.
- Each point in the output is a two-element list
[x, y]. - Coordinates are to be treated as exact decimal values. For example,
0.1means exactly one tenth, so collinearity and equality tests must not be affected by binary floating-point rounding.
Degenerate pieces
A piece whose points are all identical does not define a line. Such a piece is never joined with a piece that has two distinct points, even if it lies on that piece's line. Degenerate pieces with the same location are joined together. Each such location yields a group containing just that single point, positioned by the smallest original index among those pieces.
Constraints
1 <= len(pieces), and each piece has at least 2 points.- All points in a piece are collinear.
- Coordinates are finite decimal numbers (integers or floats with a short decimal representation).
- Duplicate points may appear within a piece and across pieces.
- Overlap is inclusive: extents
[0, 2]and[2, 5]on the same line are joined.
Examples
Example 1
Input: fuse_collinear_pieces([[[1, 1], [2, 2], [4, 4]], [[4, 2], [2, 1]], [[7, 7], [8, 8]], [[3, 3], [5, 5]]])
Output: [[[1, 1], [2, 2], [3, 3], [4, 4], [5, 5]], [[2, 1], [4, 2]], [[7, 7], [8, 8]]]
Example 2
Input: fuse_collinear_pieces([[[0, 0], [2, 0]], [[2, 0], [4, 0]], [[1, 0], [3, 0]]])
Output: [[[0, 0], [1, 0], [2, 0], [3, 0], [4, 0]]]
Example 3
Input: fuse_collinear_pieces([[[0, 0], [1, 1]], [[1, 0], [0, 1]], [[2, 2], [3, 3]]])
Output: [[[0, 0], [1, 1]], [[0, 1], [1, 0]], [[2, 2], [3, 3]]]
Hints
Hint 1
Splitting the work helps: first decide which pieces share the same infinite line, then solve a one-dimensional overlap problem on each line.
Hint 2
Build a canonical key for a line that does not depend on which two points you choose. Normalize the coefficients of a*x + b*y + c = 0 by dividing by the first nonzero one, and use exact fractions to avoid float rounding.
Hint 3
Along a line, one coordinate (x, or y for vertical lines) is enough to order points. Sort each line's pieces by their smallest coordinate and sweep, extending the current group while the next piece starts at or before the group's current right end. Track the minimum original index per group for the final ordering.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task splits into two independent parts.
-
Group pieces by their infinite line. Pieces on different lines never fuse, even if they cross. For each piece, take its first point and the first point different from it. These define the line
a*x + b*y + c = 0witha = y2 - y1,b = x1 - x2andc = -(a*x1 + b*y1). Dividing all three coefficients by the first nonzero one amonga,bgives a canonical key, so any two points on the line produce the same key. All arithmetic usesFractionbuilt from each number's decimal string, so there is no floating-point error and the keys hash consistently. -
Merge 1D intervals within each line. On a line, one coordinate fully determines position:
xfor non-vertical lines,yfor vertical ones. Each piece becomes the interval[min, max]of that coordinate over its points. Sort the intervals by start and sweep. If the next interval starts at or before the current group's right end (<=, so touching counts), it joins the group, the right end is extended, the group's smallest piece index is updated and its points are added. Otherwise a new group starts.
For each group, deduplicate the points and sort them as (x, y). On a non-vertical line this orders by x. On a vertical line all x are equal, so it orders by y.
Degenerate pieces, where all points are identical, have no line. They are grouped by their location in a separate dictionary and each location yields a single-point group.
Finally, sort all groups by their smallest original piece index and convert the coordinates back to floats.
Why it is correct
- Two pieces share a key exactly when they lie on the same infinite line, because the normalized coefficients identify the line uniquely and the arithmetic is exact.
- Along a line, the chosen coordinate is strictly monotonic, so interval overlap on that coordinate is the same as extent overlap on the line.
- The sweep handles chains. Sorted by start, once an interval begins past the group's right end, no later interval can reach back into it. So the groups are exactly the connected components of the overlap relation.
Complexity
Let P be the total number of points and n the number of pieces.
- Time:
O(P log P)for sorting the intervals and the points. - Space:
O(P)for the buckets and the output.
Reference solution
from fractions import Fraction
from typing import List
def fuse_collinear_pieces(pieces: List[List[List[float]]]) -> List[List[List[float]]]:
def as_fraction(value):
return Fraction(str(value))
def line_key(points):
x1, y1 = points[0]
second = next((p for p in points[1:] if p != points[0]), None)
if second is None:
return None
x2, y2 = second
a = y2 - y1
b = x1 - x2
c = -(a * x1 + b * y1)
scale = a if a != 0 else b
return (a / scale, b / scale, c / scale)
line_groups = {}
point_groups = {}
for index, raw_piece in enumerate(pieces):
points = [(as_fraction(p[0]), as_fraction(p[1])) for p in raw_piece]
key = line_key(points)
if key is None:
point_groups.setdefault(points[0], []).append(index)
continue
is_vertical = key[1] == 0
coords = [p[1] if is_vertical else p[0] for p in points]
line_groups.setdefault(key, []).append(
(min(coords), max(coords), index, points)
)
results = []
for point, indices in point_groups.items():
results.append((min(indices), [[float(point[0]), float(point[1])]]))
for key, items in line_groups.items():
items.sort(key=lambda item: (item[0], item[1], item[2]))
components = []
for lo, hi, index, points in items:
if not components or lo > components[-1][1]:
components.append([lo, hi, index, list(points)])
else:
comp = components[-1]
comp[1] = max(comp[1], hi)
comp[2] = min(comp[2], index)
comp[3].extend(points)
for _, _, first_index, comp_points in components:
ordered = sorted(set(comp_points))
results.append((first_index, [[float(x), float(y)] for x, y in ordered]))
results.sort(key=lambda item: item[0])
return [pts for _, pts in results]