KatInterview

Fewest Conference Rooms for a Day of Bookings

Greedy & IntervalsAuto-graded · 19 test cases
MediumAuto-gradedGreedy & Intervalsintervalssweep-linesorting

Last updated

Find the fewest rooms that can host every booking in an unordered list of half-open time ranges, where back-to-back bookings may share a room.

Fewest Conference Rooms for a Day of Bookings

A office has a list of bookings, and each booking has a start time and an end time. A room can hold only one booking at any moment, and a booking must stay in a single room from its start until its end.

Write a function that returns the smallest number of rooms that lets every booking take place in full.

Input

  • bookings: a list of pairs [start, end]. Pair i describes booking i, which occupies the half-open time range [start, end).

Output

  • An integer: the minimum number of rooms required.

Rules

  • Two bookings clash if their time ranges overlap.
  • Because ranges are half-open, a booking that ends at time t does not clash with a booking that starts at time t. Both can use the same room.
  • The bookings come in no particular order.
  • If the list is empty, return 0.

Constraints

  • 0 <= len(bookings) <= 10^5
  • 0 <= start < end <= 10^9 for every booking

Examples

Example 1

Input: min_rooms_required([[1, 5], [2, 6], [4, 8], [7, 9]])

Output: 3

Example 2

Input: min_rooms_required([[1, 3], [3, 5], [5, 7]])

Output: 1

Example 3

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

Output: 2

Hints

Hint 1

Think about a single moment in time: how many bookings are running at once? What does that say about the number of rooms needed?

Hint 2

Turn each booking into two events, one where a room becomes occupied and one where a room becomes free, then process the events in time order while keeping a running count.

Hint 3

When an end event and a start event share the same time, handle the end first so that back-to-back bookings do not count as overlapping.