KatInterview

Lowest-Numbered Free Room Booking for Time Slots

Heaps, Sorting & SearchAuto-graded · 20 test cases
MediumAuto-gradedHeaps, Sorting & Searchheapsimulationsorting

Last updated

Simulate a deterministic room-allocation process with heaps: sort by start, free finished rooms, pick the smallest free ID, and report assignments in input order.

Booking Rooms by Lowest Free Number

A building receives a list of bookings, where slots[i] = [begin_i, finish_i] describes a booking that occupies a room during the half-open time range [begin_i, finish_i). A booking that finishes at time t releases its room at that same moment, so another booking that begins at time t may use that room.

Each booking must be given a room number, and two bookings whose time ranges overlap must never share a room. The assignment follows a fixed procedure:

  1. Handle bookings in increasing order of begin. If several bookings have the same begin, handle the one with the smaller original index first.
  2. Just before handling a booking that begins at time b, every room whose current booking has finish <= b becomes free.
  3. Give the booking the free room with the smallest number (rooms are numbered from 0). If no room is free, open a new room whose number equals the count of rooms opened so far (so 0, then 1, then 2, and so on).

Return a list answer of length len(slots) where answer[i] is the room number given to slots[i], in the original input order.

Constraints

  • 1 <= len(slots) <= 10^5
  • len(slots[i]) == 2
  • 0 <= begin_i < finish_i <= 10^9

Examples

Example 1

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

Output: [0, 1, 1]

Example 2

Input: book_rooms([[1, 4], [2, 5], [4, 6]])

Output: [0, 1, 0]

Example 3

Input: book_rooms([[1, 2], [2, 3], [3, 4]])

Output: [0, 0, 0]

Hints

Hint 1

Process bookings in sorted order of (begin, original index), but remember to write each result back at its original index.

Hint 2

Keep two min-heaps: one of busy rooms keyed by finish time, and one of free room numbers. Before placing a booking, move every room with finish <= begin into the free heap.

Hint 3

Use <= (not <) when releasing rooms so back-to-back bookings reuse the same room. If the free heap is empty, open a new room numbered by how many have been opened so far.