Problem 314122 · medium · Level 03 Linear Management & Searching

Merging Bookings for One Room

intervals · sorting · greedy

Interval problems almost always start with one move: sort by start. Once sorted, an interval can only overlap the one immediately before it in the merged output, so a single pass finishes the job.

A meeting room's booking sheet lists time slots as [start, end] pairs, both ends inclusive, in no particular order. Work out when the room is busy: combine every group of overlapping slots into one, and return the resulting non-overlapping slots sorted by start. Slots that merely touch, such as [3, 6] and [6, 8], count as overlapping.

Examples

Input:  intervals = [[2, 5], [4, 9], [11, 13], [16, 20]]
Output: [[2, 9], [11, 13], [16, 20]]
Input:  intervals = [[3, 6], [6, 8]]
Output: [[3, 8]]

Constraints

  • 0 <= len(intervals) <= 10**4
  • start <= end for every interval; the input is not necessarily sorted.
  • Aim for O(n log n) time (dominated by the sort).

Goals

  • Sort intervals by start so that overlaps are always adjacent
  • Compare each interval with the last merged one and either extend it or start a new one
  • Handle touching intervals and fully-contained intervals correctly
Starting Python…