KatInterview

Collapse Overlapping Time Ranges Into Disjoint Blocks

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

Last updated

Sort closed integer ranges and sweep once to combine any that overlap or touch, returning the minimal ordered list of disjoint ranges.

You are given a list of closed ranges, each written as [start, end] with start <= end. The ranges may come in any order.

Combine ranges so that no two ranges in the result share any point, and return the result. Two ranges should be combined if they overlap, or if they touch at a single endpoint (for example, [1, 4] and [4, 5] become [1, 5]). A range completely inside another is absorbed by it.

The returned ranges must together cover exactly the same points as the input ranges, and must be sorted in ascending order by start.

Task

Implement collapse_ranges(ranges) that returns the list of disjoint ranges described above.

Rules

  • If the input list is empty, return an empty list.
  • A single range is returned unchanged.
  • Zero-length ranges such as [5, 5] are valid and are treated like any other range.
  • Ranges that only touch at an endpoint are merged.
  • Ranges separated by a gap (the next start is strictly greater than the current end) stay separate.
  • Each output range is a two-element list [start, end]. Do not modify the input list.

Constraints

  • 0 <= len(ranges) <= 10^4
  • Each range has the form [start, end] with integers 0 <= start <= end <= 10000
  • The input is not guaranteed to be sorted.

Examples

Example 1

Input: collapse_ranges([[1, 3], [2, 6], [8, 10], [15, 18]])

Output: [[1, 6], [8, 10], [15, 18]]

Example 2

Input: collapse_ranges([[1, 4], [4, 5]])

Output: [[1, 5]]

Hints

Hint 1

Order matters: if you process ranges in a convenient order, any range that can join the current block must be the very next one you look at.

Hint 2

Sort by start. Keep the last output block, and compare the next range's start with that block's end.

Hint 3

When extending a block, take the larger of the two ends, otherwise a range nested inside a bigger one would wrongly shrink it. Use `<=` for the comparison so touching ranges merge.