Coalesce Touching Segments and Measure Coverage
Greedy & IntervalsAuto-graded · 22 test casesLast updated
Merge half-open integer segments that overlap or touch end-to-start, then report the merged segments in order along with their combined covered length.
Coalesce Touching Segments and Measure Coverage
You are given a list of segments on the integer number line. Each segment is written as [start, end] and represents the half-open range that includes start but excludes end. Every segment satisfies start < end. The list is in arbitrary order and may contain duplicates.
Combine segments into larger ones according to this rule: two segments are joined into one if they overlap, or if one ends exactly where the other begins (so that together they leave no gap). Keep combining until no more joins are possible.
Return a two-element list [merged, total], where:
mergedis the list of resulting segments, each as[start, end], sorted bystartin increasing order. No two segments inmergedoverlap or touch.totalis the sum ofend - startover all segments inmerged. Overlapping parts of the input must be counted only once.
If the input list is empty, return [[], 0].
Rules to note
- A segment fully contained in another is absorbed by it; the larger segment's bounds remain.
- Segments
[a, b]and[b, c]merge into[a, c], because the first ends exactly where the second starts. - Segments
[a, b]and[b + 1, c]do not merge, since the pointbis left uncovered. - Coordinates may be negative or large.
- Identical segments collapse into one.
Constraints
0 <= len(ranges) <= 10^5- Each segment has exactly two integers
[start, end]withstart < end. - Coordinates may be negative and can be as large as 64-bit integers.
- The input list should not need to be modified.
Examples
Example 1
Input: coalesce_segments([[1, 4], [3, 5], [5, 7]])
Output: [[[1, 7]], 6]
Example 2
Input: coalesce_segments([[1, 2], [3, 4], [6, 9], [8, 10]])
Output: [[[1, 2], [3, 4], [6, 10]], 6]
Example 3
Input: coalesce_segments([[-5, -1], [-3, 2], [4, 6], [6, 8]])
Output: [[[-5, 2], [4, 8]], 11]
Hints
Hint 1
Think about what order would let you decide, for each segment, whether it can join the group you are currently building, without ever looking back at earlier groups.
Hint 2
Once the segments are ordered by start, keep one open group. A new segment joins it exactly when its start is less than or equal to the open group's end. Remember that touching counts, and that the group's end must be the larger of the two ends.
Hint 3
Do not add up the lengths of the original segments, since overlaps would be counted twice. Compute the total from the final merged, non-overlapping segments.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Sort the segments by their start value, then sweep through them once while maintaining a single "open" group defined by (open_start, open_end).
For each next segment [start, end]:
- If
start <= open_end, the segment overlaps or touches the open group. Extend the group by settingopen_end = max(open_end, end). - Otherwise there is a genuine gap (at least the point
open_endis uncovered). Finalize the open group, append it to the result, and start a new group from this segment.
After the loop, append the last open group. Finally, add up end - start over the merged groups to get the total coverage.
Why it is correct
- Sorted order means no looking back. Every later segment starts at or after the current one, so once a gap appears before a segment, no later segment can reach back across it. A finalized group is therefore truly final.
- The
<=test handles adjacency. With half-open ranges,[3,5)and[5,7)share no point but leave no gap, so they must merge. Using<would wrongly keep them apart. - The
maxhandles containment. A later segment may lie entirely inside the open group (for example[2,3]inside[1,10]), and must not shrink the group's end. - The total is computed from merged groups. They are disjoint, so each covered point is counted exactly once. Summing the raw input lengths would double-count overlaps.
- Duplicates and ties. Segments with the same start always end up in the same group, and the group's end is a maximum, so their relative order does not affect the result.
Complexity
- Time: O(n log n), dominated by sorting. The sweep and the final sum are O(n).
- Space: O(n) for the sorted copy and the output. The sweep itself uses O(1) extra space. The input list is not modified.
Reference solution
from typing import List
def coalesce_segments(segments: List[List[int]]) -> List:
if not segments:
return [[], 0]
ordered = sorted(segments, key=lambda seg: seg[0])
merged = []
open_start, open_end = ordered[0]
for start, end in ordered[1:]:
if start <= open_end:
if end > open_end:
open_end = end
else:
merged.append([open_start, open_end])
open_start, open_end = start, end
merged.append([open_start, open_end])
total = sum(end - start for start, end in merged)
return [merged, total]