KatInterview

Coalesce Touching Segments and Measure Coverage

Greedy & IntervalsAuto-graded · 22 test cases
MediumAuto-gradedGreedy & Intervalsintervalssortingsweep

Last 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:

  • merged is the list of resulting segments, each as [start, end], sorted by start in increasing order. No two segments in merged overlap or touch.
  • total is the sum of end - start over all segments in merged. 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 point b is 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] with start < 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.