Squeeze In a Booking

Medium · Greedy & Intervals · about 20 min

A meeting room's bookings are [start, end] pairs (whole minutes, start ≤ end). The list is sorted by start and no two bookings overlap or touch. A new booking booking arrives.

Add it and merge every booking that overlaps it or touches it (one ends at the minute the other starts, like [1, 3] and [3, 5]). Return the updated list, sorted by start, with no two bookings overlapping or touching. [1, 2] and [3, 4] do not touch, so they stay apart.

  • 0 to 10^5 bookings. Aim for one pass, O(n). Return a new list.

add_booking([[1, 2], [4, 6], [8, 9]], [5, 8]) → [[1, 2], [4, 9]]

Hints

  • Bookings that end before the new one starts are untouched: copy them first.
  • Every following booking whose start is at or before the new end must be merged: take the smaller start and the larger end.
  • Add the merged booking, then copy whatever is left.

Learn the pattern first: the Greedy & Intervals lesson.

More Greedy & Intervals problems