KatInterview

Collapse Booked Time Ranges Into Disjoint Blocks

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

Last updated

Combine closed integer ranges that overlap or share an endpoint into disjoint blocks, tests sorting plus a single sweep and careful boundary handling.

You are given a list of closed ranges, where each range is a two-element list [start, end] of integers with start <= end. Produce the smallest list of ranges that covers exactly the same set of points as the input, by combining ranges that belong together.

Two ranges belong together if they share at least one point. Ranges that merely touch at an endpoint count as sharing that point, so [1, 4] and [4, 5] combine into [1, 5]. A range fully inside another is absorbed by it. Combining is transitive: if A joins B and B joins C, all three become a single range.

Task

Implement a function that takes the list of ranges and returns the list of combined, pairwise disjoint ranges.

Output format

  • Return a list of [start, end] lists.
  • The result must be sorted in ascending order of start.
  • No two returned ranges may overlap or touch.
  • If the input is empty, return an empty list.
  • The input list should not be modified.

Constraints

  • 0 <= len(intervals) <= 10^4
  • Each range has exactly two integers, start <= end.
  • Values may be negative or zero, and fit in a standard 32-bit signed integer.
  • The input may be unsorted and may contain duplicates and single-point ranges such as [5, 5].

Examples

Example 1

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

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

Example 2

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

Output: [[1, 5]]

Hints

Hint 1

Ranges that can combine are hard to spot when they are in arbitrary order. What ordering would put them next to each other?

Hint 2

After ordering by start, a new range can only interact with the most recently built block. Compare its start with that block's end.

Hint 3

When extending a block, do not simply copy the new end. A range may sit entirely inside the block, so keep the larger of the two ends. Use a less-than-or-equal comparison so touching ranges merge.