KatInterview

Smallest-ID Room Allocation for Booking Time Slots

Greedy & IntervalsAuto-graded · 22 test cases
MediumAuto-gradedGreedy & Intervalsintervalsheapgreedy

Last updated

Partition half-open time intervals across the fewest resources, deterministically giving each booking the lowest-numbered free resource, using sorting and two heaps.

Allocate Rooms to Bookings

A venue receives a list of bookings. Booking i is given as bookings[i] = [start_i, end_i] and uses a room during the half-open time span [start_i, end_i). A room that is released at time end_i can be given to another booking that starts at any time >= end_i.

Assign every booking to a room so that:

  1. Two bookings placed in the same room never overlap in time.
  2. The number of rooms used is as small as possible.
  3. The allocation is deterministic. Bookings are handled in ascending order of start; bookings with the same start are handled in ascending order of their original index.
  4. When a booking is handled, if one or more rooms are free, it takes the free room with the smallest room number. If no room is free, it takes the smallest room number that has never been used. Rooms are numbered 1, 2, 3, ....

A room counts as free for a booking starting at time t if every booking previously placed in it has an end that is <= t.

Return a tuple (room_count, assignment), where room_count is the minimum number of rooms needed and assignment[i] is the room number given to booking i (in the original input order).

If bookings is empty, return (0, []).

Constraints

  • 0 <= len(bookings) <= 10^5
  • 0 <= start_i < end_i <= 10^9
  • All values are integers.
  • Rooms released at time t must be treated as free for any booking that starts at time t.

Examples

Example 1

Input: allocate_rooms([[1, 4], [2, 5], [4, 7], [3, 6]])

Output: [3, [1, 2, 1, 3]]

Example 2

Input: allocate_rooms([[1, 3], [3, 5]])

Output: [1, [1, 1]]

Hints

Hint 1

Process bookings in sorted order of (start, original index), but write each result back to the booking's original position.

Hint 2

Keep a min-heap of occupied rooms keyed by end time, so you can find every room that has been released by the current start time.

Hint 3

A heap keyed by end time alone cannot tell you the smallest free room number. Move all released rooms (end <= start) into a second min-heap of free room numbers, and pop the smallest from it.