Union Overlapping Road Pieces That Share a Straight Line
Greedy & IntervalsAuto-graded · 23 test casesLast updated
Group integer-point polylines by the exact line they lie on, then merge overlapping or touching extents on each line into one sorted point list.
You are given a collection of straight road pieces. Each piece is a list of integer points [x, y] that all lie on a single straight line. Several pieces may lie on the same line and may overlap. Combine every group of overlapping pieces on a common line into a single piece that contains all of their points, and return the resulting pieces.
Your function must work for every orientation, including horizontal and vertical pieces.
Rules
- Two pieces are on the same line when all of their points are collinear. Pieces on different lines are never combined, even if they cross, touch, or are parallel.
- The span of a piece is the closed stretch of its line running from its first point to its last point. Two pieces on the same line overlap when their spans share at least one point. Sharing just one endpoint counts as overlapping.
- Combining is transitive: if A overlaps B and B overlaps C, then A, B and C become one piece, even if A and C do not overlap each other.
- Every output piece, combined or not, is the list of the distinct points from all of its member pieces, sorted by
xascending and then byyascending. - Output order: group output pieces by line, and order the lines by the index of the first input piece that lies on each line. Within one line, order the output pieces by their first point (by
x, then byy).
Input
pieces: a list of pieces. Each piece is a list of points, and each point is a list[x, y]of two integers.
Output
A list of merged pieces in the order described above. Each piece is a list of [x, y] points.
Constraints
1 <= len(pieces) <= 10^42 <= len(pieces[i]) <= 100, and the total number of points over all pieces is at most10^5.- Every coordinate is an integer in
[-10^4, 10^4]. - Within a piece, the points are distinct, collinear, and already sorted by
xascending and then byyascending. - Different pieces may share points or be identical.
Examples
Example 1
Input: merge_road_pieces([[[1, 1], [2, 2], [4, 4]], [[2, 1], [4, 2]], [[3, 3], [6, 6]], [[7, 7], [8, 8]]])
Output: [[[1, 1], [2, 2], [3, 3], [4, 4], [6, 6]], [[7, 7], [8, 8]], [[2, 1], [4, 2]]]
Example 2
Input: merge_road_pieces([[[0, 0], [2, 0]], [[1, -2], [1, 0]], [[2, 0], [5, 0]], [[1, 3], [1, 5]], [[6, 0], [7, 0]]])
Output: [[[0, 0], [2, 0], [5, 0]], [[6, 0], [7, 0]], [[1, -2], [1, 0]], [[1, 3], [1, 5]]]
Example 3
Input: merge_road_pieces([[[0, 0], [2, 1], [6, 3]], [[0, 1], [2, 2]], [[2, 1], [4, 2]]])
Output: [[[0, 0], [2, 1], [4, 2], [6, 3]], [[0, 1], [2, 2]]]
Hints
Hint 1
Avoid floating-point slopes: vertical pieces break the division and rounding can make equal slopes look different. Describe a line with integers only.
Hint 2
Reduce the direction vector between a piece's first two points by their gcd, fix its sign so it is unique, and add an offset such as dy*x0 - dx*y0 so parallel lines get different keys.
Hint 3
After the sign fix, ordering points by (x, y) matches their order along the line, so each piece is an interval you can compare with tuples. Sort by start and sweep, treating start <= current end as overlapping.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task has two stages: decide which pieces share a line, then merge overlapping spans on each line.
1. Identify each line with an exact integer key.
- Take the direction
(dx, dy)from a piece's first two points. The points are distinct, so it is never(0, 0). - Divide both components by
gcd(dx, dy)so all directions along one line reduce to the same primitive vector. - Fix the sign: require
dx > 0, ordx == 0anddy > 0. - Compute the offset
c = dy*x0 - dx*y0. It is the same for every point on the line, and differs between parallel lines.
The key (dx, dy, c) identifies the line. Horizontal pieces reduce to direction (1, 0) and vertical ones to (0, 1), so no special cases or divisions by zero occur.
2. Merge spans on each line. After the sign fix, tuple order (x, y) equals order along the line. Each piece is therefore a closed interval [first, last]. Sort the pieces of a line by first point and sweep, keeping the running end. A piece joins the current group if its first point is <= the running end (touching counts); otherwise it starts a new group. This gives transitive merging automatically.
3. Emit groups. For each group, take the union of its points, sort them, and output. Lines are emitted in order of first appearance in the input.
Why it is correct
- The offset
cis invariant along a line, since substituting(x0 + t*dx, y0 + t*dy)givesdy*x0 - dx*y0for everyt. - The reduced, sign-fixed direction is unique per orientation, and same-direction lines coincide exactly when
cmatches. So two pieces share a line iff their keys match, and the first two points suffice because all points of a piece are collinear. - With
dx > 0thexcoordinate increases along the line, and withdx == 0theycoordinate does, so lexicographic order equals position order. The first and last points of each sorted piece are its span endpoints. - The sweep is the standard interval merge with an inclusive test; every member of a group intersects the contiguous union built so far, which yields chains like A-B-C.
- Groups on a line are created in increasing order of their smallest start point, which matches the required within-line order.
Complexity
With S pieces and P total points:
- Time:
O(S log S + P log P). - Space:
O(S + P).
Reference solution
from math import gcd
def merge_road_pieces(pieces):
lines = {}
order = []
for piece in pieces:
(x0, y0), (x1, y1) = piece[0], piece[1]
dx, dy = x1 - x0, y1 - y0
g = gcd(dx, dy)
dx //= g
dy //= g
if dx < 0 or (dx == 0 and dy < 0):
dx, dy = -dx, -dy
key = (dx, dy, dy * x0 - dx * y0)
if key not in lines:
lines[key] = []
order.append(key)
lines[key].append(piece)
result = []
for key in order:
group_pieces = sorted(lines[key], key=lambda s: (s[0][0], s[0][1]))
groups = []
cur = None
end = None
for s in group_pieces:
first = (s[0][0], s[0][1])
last = (s[-1][0], s[-1][1])
if cur is not None and first <= end:
cur.append(s)
if last > end:
end = last
else:
cur = [s]
groups.append(cur)
end = last
for grp in groups:
pts = set()
for s in grp:
for p in s:
pts.add((p[0], p[1]))
result.append([[x, y] for x, y in sorted(pts)])
return result