KatInterview

Fewest Conference Rooms for a Day of Bookings

Greedy & IntervalsAuto-graded · 20 test cases
MediumAuto-gradedGreedy & Intervalsintervalsheapsweep-line

Last updated

Compute the minimum number of rooms needed to host all time-range bookings when back-to-back bookings may reuse a room, testing sweep-line or heap-based interval reasoning.

Fewest Conference Rooms for a Day of Bookings

You manage a building's conference rooms and receive a list of bookings. Each booking is a pair [start, end] of integers with start < end, giving the time the booking begins and the time it finishes.

Treat each booking as occupying the half-open time span from start up to, but not including, end. So a booking that finishes at time 10 and another that begins at time 10 do not clash, and the same room can serve both one after the other.

Write a function that returns the smallest number of rooms needed so that every booking is assigned to a room and no room ever hosts two bookings whose time spans overlap.

Rules

  • The bookings may be given in any order, and several bookings may be identical.
  • If the list is empty, the answer is 0.
  • Return a single integer.

Constraints

  • 0 <= len(bookings) <= 10^5
  • Each booking is [start, end] with integers and start < end
  • Bookings are not guaranteed to be sorted
  • Bookings that share only an endpoint (one ends exactly when another starts) do not overlap

Examples

Example 1

Input: min_rooms_required([[9, 10], [9, 12], [11, 13], [14, 15]])

Output: 2

Example 2

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

Output: 2

Hints

Hint 1

Think about the moment in time when the most bookings are running at once. That peak count is the number of rooms you need.

Hint 2

Sort the bookings by start time. As you go, you need to know whether any room that is already in use has become free by the current start time.

Hint 3

Keep a min-heap of end times of rooms in use. Before adding a booking, pop every end time that is less than or equal to its start (equal means the room is free). The largest heap size seen is the answer.