KatInterview

Fewest Rooms to Host All Bookings

Greedy & IntervalsAuto-graded · 23 test cases
MediumAuto-gradedGreedy & Intervalsintervalsmin-heapsorting

Last updated

Find the smallest number of rooms that can host every booking at once, where a booking may begin the moment another one ends, using sorting and a min-heap.

Fewest Rooms to Host All Bookings

A venue receives a list of bookings. Each booking is a pair [start, end] of integers with start < end, meaning the room is occupied from time start until time end.

Return the smallest number of rooms that lets every booking be assigned to a room so that no room ever holds two bookings at the same moment.

Rules

  • Two bookings in the same room conflict only if their time ranges overlap for a positive length. A booking that ends at time t and another that starts at time t do not conflict and may share a room.
  • Identical bookings are separate bookings. Two copies of [3, 8] need two rooms.
  • The input list is in no particular order.
  • If the list is empty, return 0.

Function

Implement rooms_needed(bookings), where bookings is a list of [start, end] pairs. It returns a single integer: the minimum number of rooms.

Constraints

  • 0 <= len(bookings) <= 10^5
  • Each booking has exactly two integers, start < end
  • Times are integers that fit in a normal 32-bit signed range
  • The input list may be unsorted and may contain duplicates
  • Do not rely on the input being modified. Work on a copy if you reorder it.

Examples

Example 1

Input: rooms_needed([[0, 30], [5, 10], [15, 20]])

Output: 2

Example 2

Input: rooms_needed([[7, 10], [10, 12]])

Output: 1

Example 3

Input: rooms_needed([[1, 5], [2, 6], [3, 7], [8, 9]])

Output: 3

Hints

Hint 1

Think about the busiest moment: the answer equals the largest number of bookings that are in progress at the same time.

Hint 2

Process bookings in order of start time. Keep track of the end times of the bookings currently occupying rooms, and be able to quickly find the one that finishes earliest.

Hint 3

A min-heap of end times works well. Before adding a new booking, remove every end time that is less than or equal to its start (touching is allowed). The largest heap size seen is the answer.