Deterministic Room Allocation for Intervals

Medium · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

Given a list of bookings meetings, each entry meetings[i] = [start_i, end_i] spans the half-open time window [start_i, end_i). Because the upper endpoint is exclusive, a room whose current session finishes at timestamp t becomes vacant right at t and can immediately host another session beginning at t.

Allocate a room to every booking so that overlapping sessions never share a room, obeying three deterministic rules:

  • Processing order: Handle bookings in non-decreasing order of start_i, breaking ties between identical start times by smaller input index i.
  • Releasing rooms: Right before placing a booking that starts at start_i, mark every busy room whose active session satisfies end <= start_i as vacant.
  • Lowest ID selection: Choose the vacant room with the lowest non-negative integer ID (0, 1, 2, ...). Whenever every existing room is busy, open a brand-new room whose ID equals the count of rooms opened up to that moment.

Implement assign_rooms(meetings: List[List[int]]) -> List[int] and return an integer list of length len(meetings) whose i-th element is the room ID allocated to meetings[i].

Examples

Example 1

Input: meetings = [[2, 25], [6, 12], [14, 19], [1, 5]]
Output: [1, 0, 0, 0]

Walk-through: - Sorting by (start_i, i) processes indices in the order 3, 0, 1, 2. - Booking 3 ([1, 5)) opens room 0. - Booking 0 ([2, 25)) arrives while room 0 is busy until 5, so it opens room 1. - Booking 1 ([6, 12)) arrives after [1, 5) finishes at 5, reclaiming free room 0. - Booking 2 ([14, 19)) arrives after [6, 12) finishes at 12, reclaiming free room 0 again. - Writing room IDs back to input indices 0..3 yields [1, 0, 0, 0].

Example 2

Input: meetings = [[3, 8], [3, 6], [8, 11], [9, 12]]
Output: [0, 1, 0, 1]

Walk-through: - Bookings 0 and 1 both start at 3; smaller index 0 goes first into room 0, and booking 1 opens room 1. - By timestamp 8, both [3, 6) and [3, 8) have finished (6 <= 8 and 8 <= 8), leaving rooms 0 and 1 vacant. Booking 2 ([8, 11)) takes the smaller ID, room 0. - At timestamp 9, room 0 is busy until 11 while room 1 remains vacant, so booking 3 ([9, 12)) takes room 1.

Example 3

Input: meetings = [[10, 15], [15, 20], [0, 10], [20, 25]]
Output: [0, 0, 0, 0]

Walk-through: - Ordered by start time ([0, 10), [10, 15), [15, 20), [20, 25)), each session starts right as the previous one ends, so room 0 serves all four bookings.

Constraints

  • 1 <= len(meetings) <= 10^5
  • len(meetings[i]) == 2
  • 0 <= start_i < end_i <= 10^9

Step-by-step walkthrough

  1. Understand the problem and rules

    Each entry meetings[i] = [start, end] represents a half-open interval [start, end): the room is occupied beginning at start and turns vacant right at end. Because end is excluded, consecutive bookings can share the exact same room:

    Time:       3     4     5     6     7     8     9    10    11
    Booking 0:  [-----------------------------o                    [3, 8) vacates at t = 8
    Booking 2:                                [-----------------o  [8, 11) can reuse that room
    

    We need to return an array result of length len(meetings) where result[i] holds the room ID allocated to meetings[i] at its original input index, obeying three rules:

    1. Scheduling order: Handle bookings by non-decreasing start. Break ties between equal start values using the smaller input index i.
    2. Release completed sessions: Before assigning a booking at start, every active session with end <= start vacates its room.
    3. Lowest ID priority: Pick the lowest free integer ID (0, 1, 2, ...). Only when zero rooms are vacant do we open a new room whose ID equals the count of rooms opened so far.

    With up to 10^5 bookings, we aim for O(n log n) time.

  2. Why scanning rooms directly is too slow

    A direct brute-force approach sorts bookings into the required processing order and maintains a list of rooms. Whenever a booking arrives, it checks room 0, room 1, room 2, and so forth until finding one whose prior session ended by start, or appends a brand-new room.

    That logic is useful as a small test oracle, yet look at what happens if all 100,000 bookings span [0, 1000):

    • Booking 0 inspects 0 rooms and opens room 0.
    • Booking 1 inspects 1 busy room and opens room 1.
    • Booking 99,999 inspects 99,999 busy rooms and opens room 99,999.

    Total room inspections reach 0 + 1 + 2 + ... + 99,999, roughly 5 * 10^9 checks, exceeding time limits.

    Notice that each arriving booking really only needs rapid answers to two questions:

    1. Which currently busy rooms have end <= start so we can vacate them right now?
    2. Out of all currently vacant rooms, which one carries the smallest room_id?
  3. Key idea: maintain two min-heaps

    A min-heap is a tree-based priority queue (available in Python's heapq module) that keeps its minimum element at index 0, supporting O(1) minimum lookup and O(log k) insertion or removal.

    Maintaining two cooperating min-heaps answers both questions in logarithmic time:

    • occupied_rooms: a min-heap of (end_time, room_id) pairs for sessions currently running. Because Python orders tuples from left to right, occupied_rooms[0] always holds the running session that finishes soonest.
    • available_rooms: a min-heap of vacant room_id integers, so available_rooms[0] is always the lowest vacant room ID.

    Why isn't a plain queue or stack enough for vacant rooms? Compare [[0, 5], [0, 3], [6, 7]] against [[0, 3], [0, 5], [6, 7]]:

    Case A: [[0, 5], [0, 3], [6, 7]]
      t = 0: room 0 busy until 5, room 1 busy until 3
      t = 6: room 1 finished earlier (at 3), room 0 finished later (at 5)
             both {0, 1} are free -> a FIFO queue would wrongly hand out room 1!
    
    Case B: [[0, 3], [0, 5], [6, 7]]
      t = 0: room 0 busy until 3, room 1 busy until 5
      t = 6: room 0 finished earlier (at 3), room 1 finished later (at 5)
             both {0, 1} are free -> a LIFO stack would wrongly hand out room 1!
    

    Only a min-heap (available_rooms) selects room 0 in both cases regardless of completion order.

    Why does this rule also minimize the total room count? Room k is created only when available_rooms is empty at start_time, meaning all k existing rooms (0 .. k - 1) hold running sessions with end_time > start_time. Along with the arriving booking, k + 1 sessions overlap at start_time, proving that no conflict-free schedule can use fewer than k + 1 rooms.

  4. Sort bookings while preserving original indices

    Sorting meetings in place would erase each booking's original index i, and sorting [start, end] pairs directly would break same-start ties by end rather than by input index.

    Instead, we build (start_time, original_index) pairs and sort them. Tuple comparison orders by start_time first and breaks ties by original_index.

        # Phase 1: Pair each meeting's start time with its original index so sorting
        # orders by start time first and breaks ties by smaller original index.
        # processing_order: list of (start_time, original_index), e.g. [(1, 3), (2, 0), (6, 1), (14, 2)]
        processing_order: List[Tuple[int, int]] = []
        for original_index in range(len(meetings)):
            start_time = meetings[original_index][0]
            processing_order.append((start_time, original_index))
        processing_order.sort()
    
  5. Vacate finished rooms and assign the smallest ID

    Next we sweep through processing_order one booking at a time:

    1. Vacate: While occupied_rooms is non-empty and occupied_rooms[0][0] <= start_time, pop (finished_end, freed_room) and push freed_room onto available_rooms. Using while (rather than if) releases every room finished by start_time, and <= (rather than <) enforces half-open intervals [start, end).
    2. Assign: Pop the lowest ID from available_rooms when non-empty; otherwise allocate rooms_created and increment rooms_created.
    3. Record: Store assigned_room at result[original_index] and push (end_time, assigned_room) onto occupied_rooms.
        result: List[int] = [0] * len(meetings)
        occupied_rooms: List[Tuple[int, int]] = []
        available_rooms: List[int] = []
        rooms_created = 0
    
        for start_time, original_index in processing_order:
            end_time = meetings[original_index][1]
    
            while occupied_rooms and occupied_rooms[0][0] <= start_time:
                finished_end, freed_room = heapq.heappop(occupied_rooms)
                heapq.heappush(available_rooms, freed_room)
    
            if available_rooms:
                assigned_room = heapq.heappop(available_rooms)
            else:
                assigned_room = rooms_created
                rooms_created += 1
    
            result[original_index] = assigned_room
            heapq.heappush(occupied_rooms, (end_time, assigned_room))
    
  6. Walk through Examples 1 and 2

    First trace Example 1: meetings = [[2, 25], [6, 12], [14, 19], [1, 5]].

    processing_order = [(1, 3), (2, 0), (6, 1), (14, 2)]
    
    1) (start=1, idx=3), end=5
       vacate: occupied_rooms is [] -> nothing freed
       available_rooms is [] -> open room 0 (rooms_created = 1)
       result[3] = 0, occupied_rooms = [(5, 0)]
    
    2) (start=2, idx=0), end=25
       vacate: top is (5, 0); 5 <= 2 is False -> nothing freed
       available_rooms is [] -> open room 1 (rooms_created = 2)
       result[0] = 1, occupied_rooms = [(5, 0), (25, 1)]
    
    3) (start=6, idx=1), end=12
       vacate: top is (5, 0); 5 <= 6 is True -> pop (5, 0), push 0 into available_rooms
               next top is (25, 1); 25 <= 6 is False -> stop
       available_rooms is [0] -> pop room 0
       result[1] = 0, occupied_rooms = [(12, 0), (25, 1)]
    
    4) (start=14, idx=2), end=19
       vacate: top is (12, 0); 12 <= 14 is True -> pop (12, 0), push 0 into available_rooms
       available_rooms is [0] -> pop room 0
       result[2] = 0, occupied_rooms = [(19, 0), (25, 1)]
    
    Final result = [1, 0, 0, 0]
    

    Now trace Example 2: meetings = [[3, 8], [3, 6], [8, 11], [9, 12]].

    1) (start=3, idx=0), end=8  -> tie at t=3 goes to idx 0 -> room 0, occupied = [(8, 0)]
    2) (start=3, idx=1), end=6  -> 8 <= 3 is False          -> room 1, occupied = [(6, 1), (8, 0)]
    3) (start=8, idx=2), end=11 -> 6 <= 8 and 8 <= 8 both free rooms 1 and 0 -> available = [0, 1]
                                   pop smallest ID 0        -> room 0, occupied = [(11, 0)], available = [1]
    4) (start=9, idx=3), end=12 -> 11 <= 9 is False, pop 1  -> room 1, occupied = [(11, 0), (12, 1)]
    
    Final result = [0, 1, 0, 1]
    
  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    import heapq
    
    
    def assign_rooms(meetings: List[List[int]]) -> List[int]:
        # Phase 1: Pair each meeting's start time with its original index so sorting
        # orders by start time first and breaks ties by smaller original index.
        # processing_order: list of (start_time, original_index), e.g. [(1, 3), (2, 0), (6, 1), (14, 2)]
        processing_order: List[Tuple[int, int]] = []
        for original_index in range(len(meetings)):
            start_time = meetings[original_index][0]
            processing_order.append((start_time, original_index))
        processing_order.sort()
    
        # result[i] stores the room ID assigned to meetings[i] in original input order.
        result: List[int] = [0] * len(meetings)
    
        # occupied_rooms: min-heap of (end_time, room_id) for meetings currently in progress,
        # ordered so the meeting finishing earliest sits at occupied_rooms[0].
        occupied_rooms: List[Tuple[int, int]] = []
    
        # available_rooms: min-heap of free integer room IDs (e.g. [0, 2]),
        # ordered so the smallest free room ID sits at available_rooms[0].
        available_rooms: List[int] = []
    
        # Total number of rooms opened so far; also the ID for the next brand-new room.
        rooms_created = 0
    
        # Phase 2: Sweep through meetings in deterministic start-time order.
        for start_time, original_index in processing_order:
            end_time = meetings[original_index][1]
    
            # Vacate every room whose meeting has finished by start_time.
            # Use <= (not <) because [start, end) is half-open: a meeting ending at t
            # frees its room immediately for a meeting starting at t.
            while occupied_rooms and occupied_rooms[0][0] <= start_time:
                finished_end, freed_room = heapq.heappop(occupied_rooms)
                heapq.heappush(available_rooms, freed_room)
    
            # Assign the smallest available room ID, or open a new room if all are busy.
            if available_rooms:
                assigned_room = heapq.heappop(available_rooms)
            else:
                assigned_room = rooms_created
                rooms_created += 1
    
            # Record the answer at the meeting's original position and mark the room busy.
            result[original_index] = assigned_room
            heapq.heappush(occupied_rooms, (end_time, assigned_room))
    
        return result
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine running the reception desk at a conference venue with rooms numbered 0, 1, 2, .... Every booking [start, end) is a half-open interval, meaning a group holds the room from start until just before end so the next group can walk in right at end. Rather than checking doors down the corridor on every arrival, you maintain two self-sorting trays — each backed by a min-heap, a tree-based priority queue that keeps its smallest element on top and updates in logarithmic time. One tray (occupied_rooms) orders busy rooms by earliest end_time, while the second tray (available_rooms) orders vacant rooms by smallest room_id.

Scanning rooms 0, 1, 2, ... linearly for each arriving booking breaks down under heavy overlap: when 100,000 sessions run simultaneously, each newcomer inspects every already-busy room before opening one more, totaling around 5 billion checks. Using only a single min-heap of end times (or keeping vacant rooms in a FIFO queue or LIFO stack) also fails, because it hands out whichever room happened to vacate earliest or latest instead of guaranteeing the lowest free integer ID.

Trace meetings = [[3, 8], [3, 6], [8, 11], [9, 12]]:

  1. At t = 3, bookings 0 ([3, 8)) and 1 ([3, 6)) tie on start time; index 0 goes first into new room 0 ((8, 0)), and index 1 opens room 1 ((6, 1)).
  2. At t = 8, booking 2 ([8, 11)) arrives. Both (6, 1) and (8, 0) satisfy end <= 8 and move into available_rooms, which pops the smaller ID 0 for booking 2.
  3. At t = 9, booking 3 ([9, 12)) arrives while (11, 0) is still busy, pops vacant room 1 from available_rooms, and yields [0, 1, 0, 1].

Complexity

  • Time: O(n log n). Building and sorting the n (start_time, original_index) pairs takes O(n log n) time. Across the sweep, each of the n bookings is pushed to and popped from occupied_rooms at most once, and each freed room ID enters and leaves available_rooms at most once per booking; every heap operation costs O(log n) because neither heap ever holds more than n items.
  • Space: O(n). Storing processing_order, result, and both heaps uses O(n) memory even when all n bookings overlap in n separate rooms.

Edge cases

  • Back-to-back sessions ([[10, 15], [15, 20], [0, 10], [20, 25]]): every session begins right at the previous session's end (end == start), so all four share room 0 ([0, 0, 0, 0]).
  • Tied start times ([[5, 8], [1, 5], [5, 6]]): booking 1 vacates room 0 at t = 5; between bookings 0 and 2 starting at 5, smaller index 0 runs first and claims room 0, giving [0, 0, 1].
  • Identical intervals ([[1, 5], [1, 5], [1, 5]]): none can share a room, opening rooms 0, 1, 2 in index order.
  • Several rooms vacating in reverse ID order ([[0, 5], [0, 3], [6, 7]]): room 1 finishes before room 0, yet by t = 6 both sit in available_rooms and room 0 wins.
  • Scrambled input order: pairing each start time with original_index before sorting ensures assignments land at their original positions in result.
  • Single booking: opens room 0 and returns [0].

Common mistakes

  • Using < instead of <= when releasing rooms: writing occupied_rooms[0][0] < start_time treats intervals as closed [start, end] and wastes an extra room on back-to-back bookings.
  • Using if instead of while when releasing rooms: multiple active sessions can finish before the next start time, and popping only one leaves vacant rooms trapped inside occupied_rooms.
  • Keeping only one heap: popping directly from occupied_rooms whenever occupied_rooms[0][0] <= start_time minimizes room count, yet overlooks other already-finished rooms that carry a smaller room_id.
  • Tracking free rooms in a list, stack, or queue: stacks return the most recently vacated room and queues return the earliest vacated room; neither guarantees the minimum integer ID.
  • Sorting meetings without original indices: sorting [start, end] pairs loses output positions and breaks start-time ties by end rather than original_index.

Alternative approaches

  • Boundary event sweep (room count only): when only the count of rooms is requested, turning each [start, end) into (end, -1) and (start, +1) events, sorting them, and tracking the peak prefix sum runs in O(n log n) time without tracking specific room IDs.
  • Linear room scan (brute force): checking rooms 0, 1, 2, ... per sorted booking obeys every rule cleanly for small inputs, but degrades to O(n^2) time under heavy overlap.

Follow-up questions

  • What changes are needed when every booking specifies a headcount and each room has a maximum seating limit? Replace the available_rooms min-heap with a balanced binary search tree (a sorted tree structure supporting search, insertion, and deletion in O(log R) time) ordered by (room_capacity, room_id), and assign each booking to the tightest free room satisfying room_capacity >= headcount ("best fit"). Note that this greedy algorithm (choosing the locally best option at each step without looking ahead) is a fast online heuristic rather than globally optimal under fixed room inventory: with rooms of size 1 and 2 and bookings A (size 1, [0, 2)), B (size 1, [1, 10)), and C (size 2, [3, 4)), best fit puts A in size 1 and B in size 2, blocking C at t = 3, whereas putting A in size 2 and B in size 1 fits all three. Exact feasibility on small inputs requires backtracking or integer linear programming.
  • How can the scheduler handle live meetings that request extra time before they finish? Extending an in-progress booking raises its end time inside occupied_rooms, which is cleanly handled via lazy deletion — leaving stale (old_end, room_id) pairs in the heap and skipping them once they reach the top. Record each active room's latest checkout in a dictionary current_end[room_id], push (new_end, room_id) onto occupied_rooms on an extension, and ignore any popped tuple where end_time != current_end[room_id]. If future bookings were already promised specific rooms ahead of time, extending past the next booking's start forces either rejecting the extension or migrating the upcoming booking to another vacant room.
  • How would you architect this allocator as an online service processing an unbounded stream of booking requests? When requests arrive in timestamp order, completed bookings never need to be revisited, dropping memory from O(n) to O(R) where R is peak concurrency. To tolerate small network jitter on arrival times, hold incoming events briefly behind a watermark (a sliding timestamp threshold up to which the service buffers slightly late arrivals before sorting and assigning that window). Partition independent room pools (such as separate office buildings) across worker shards, checkpoint heap state and assignments to durable storage for crash recovery, and require an idempotency key (a unique client-supplied token stored by the server so retrying a timed-out call returns the original room assignment instead of double-booking).

Follow-up questions

Similar questions

More Uber interview questions

All 217 Uber questions →