KatInterview

Coalesce Overlapping Ranges Into Disjoint Spans

Greedy & IntervalsAuto-graded · 25 test cases
MediumAuto-gradedGreedy & Intervalsintervalssortinggreedy

Last updated

Combine unsorted inclusive integer ranges that share at least one point into disjoint spans ordered by start, testing endpoint handling, chained merges, and nesting.

You are given a collection of inclusive integer ranges. Combine all ranges that are connected through shared points, and return the resulting set of non-overlapping ranges.

Each range is a two-element list [start, end] with start <= end. It covers every point from start through end, including both ends.

Task

Implement coalesce_ranges(ranges), which returns the combined ranges in ascending order of start.

Rules

  • The input can be in any order. It may contain repeated ranges and ranges fully contained in other ranges.
  • Two ranges are connected if they have at least one point in common. Ranges that meet at a single endpoint, such as [1, 3] and [3, 5], share the point 3 and therefore combine into [1, 5]. Ranges such as [1, 2] and [3, 4] have no point in common, so they remain separate, even though no integer lies strictly between them.
  • Combining is transitive: if range A is connected to B and B is connected to C, then A, B and C all become one range, even if A and C share no point directly.
  • In the returned list, no two ranges share a point, the list is sorted by start ascending, and the union of the returned ranges equals the union of the input ranges exactly.
  • Each returned range is a list [start, end].

Constraints

  • 1 <= len(ranges) <= 10^5
  • -10^9 <= start <= end <= 10^9
  • All values are integers.

Examples

Example 1

Input: coalesce_ranges([[8, 10], [1, 4], [3, 6], [12, 12]])

Output: [[1, 6], [8, 10], [12, 12]]

Example 2

Input: coalesce_ranges([[1, 3], [3, 5], [6, 7]])

Output: [[1, 5], [6, 7]]

Example 3

Input: coalesce_ranges([[2, 9], [3, 4], [5, 5], [1, 2]])

Output: [[1, 9]]

Hints

Hint 1

Think about what order makes it easy to decide whether the next range connects to the ones you have already combined.

Hint 2

After ordering by start, keep one current combined range. Compare the next range's start with the current range's end, and decide carefully between a strict and a non-strict comparison for touching endpoints.

Hint 3

When a range is absorbed into the current one, the new end must be the larger of the two ends, otherwise a nested range would wrongly shrink the current span.