KatInterview

Collapse Booked Time Slots into Disjoint Blocks

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

Last updated

Combine a list of [start, end] ranges so that any that overlap or touch become one range, using sorting and a single sweep.

Collapse Booked Time Slots into Disjoint Blocks

You are given a list of booked time slots, where each slot is a two-element list [start, end]. Slots may appear in any order and may overlap one another.

Produce the smallest list of disjoint blocks that covers exactly the same time as the input slots. Two slots belong in the same block if they overlap, or if one ends at the exact moment the other begins (a shared endpoint counts as overlapping). For example, [1, 4] and [4, 5] become [1, 5].

Output rules

  • Return a list of [start, end] blocks.
  • Blocks must be sorted by start in ascending order.
  • No two returned blocks may overlap or touch.
  • If the input is empty, return an empty list.
  • A slot completely inside another slot is absorbed by it (for example, [2, 5] inside [1, 10] yields [1, 10]).
  • Duplicated slots collapse into one.

Function

Implement collapse_slots(slots), which takes the list of slots and returns the list of merged blocks.

Constraints

  • 0 <= len(slots) <= 10^4
  • 0 <= start < end <= 10^6
  • Each slot has exactly two integers, [start, end].
  • The input is not guaranteed to be sorted.

Examples

Example 1

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

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

Example 2

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

Output: [[1, 5]]

Hints

Hint 1

If the slots were ordered by start time, which slots could possibly overlap the block you are currently building?

Hint 2

Sweep through the sorted slots while tracking the most recent merged block. Decide whether the next slot starts at or before that block's end.

Hint 3

When extending a block, take the larger of the two end values so that a slot nested inside the block does not shrink it. Remember that touching endpoints must merge.