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 indexi. - Releasing rooms: Right before placing a booking that starts at
start_i, mark every busy room whose active session satisfiesend <= start_ias 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^5len(meetings[i]) == 20 <= start_i < end_i <= 10^9
Step-by-step walkthrough
Understand the problem and rules
Each entry
meetings[i] = [start, end]represents a half-open interval[start, end): the room is occupied beginning atstartand turns vacant right atend. Becauseendis 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 roomWe need to return an array
resultof lengthlen(meetings)whereresult[i]holds the room ID allocated tomeetings[i]at its original input index, obeying three rules:- Scheduling order: Handle bookings by non-decreasing
start. Break ties between equalstartvalues using the smaller input indexi. - Release completed sessions: Before assigning a booking at
start, every active session withend <= startvacates its room. - 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^5bookings, we aim forO(n log n)time.- Scheduling order: Handle bookings by non-decreasing
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, room1, room2, and so forth until finding one whose prior session ended bystart, or appends a brand-new room.That logic is useful as a small test oracle, yet look at what happens if all
100,000bookings span[0, 1000):- Booking
0inspects0rooms and opens room0. - Booking
1inspects1busy room and opens room1. - Booking
99,999inspects99,999busy rooms and opens room99,999.
Total room inspections reach
0 + 1 + 2 + ... + 99,999, roughly5 * 10^9checks, exceeding time limits.Notice that each arriving booking really only needs rapid answers to two questions:
- Which currently busy rooms have
end <= startso we can vacate them right now? - Out of all currently vacant rooms, which one carries the smallest
room_id?
- Booking
Key idea: maintain two min-heaps
A min-heap is a tree-based priority queue (available in Python's
heapqmodule) that keeps its minimum element at index0, supportingO(1)minimum lookup andO(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 vacantroom_idintegers, soavailable_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 room0in both cases regardless of completion order.Why does this rule also minimize the total room count? Room
kis created only whenavailable_roomsis empty atstart_time, meaning allkexisting rooms (0 .. k - 1) hold running sessions withend_time > start_time. Along with the arriving booking,k + 1sessions overlap atstart_time, proving that no conflict-free schedule can use fewer thank + 1rooms.Sort bookings while preserving original indices
Sorting
meetingsin place would erase each booking's original indexi, and sorting[start, end]pairs directly would break same-start ties byendrather than by input index.Instead, we build
(start_time, original_index)pairs and sort them. Tuple comparison orders bystart_timefirst and breaks ties byoriginal_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()Vacate finished rooms and assign the smallest ID
Next we sweep through
processing_orderone booking at a time:- Vacate: While
occupied_roomsis non-empty andoccupied_rooms[0][0] <= start_time, pop(finished_end, freed_room)and pushfreed_roomontoavailable_rooms. Usingwhile(rather thanif) releases every room finished bystart_time, and<=(rather than<) enforces half-open intervals[start, end). - Assign: Pop the lowest ID from
available_roomswhen non-empty; otherwise allocaterooms_createdand incrementrooms_created. - Record: Store
assigned_roomatresult[original_index]and push(end_time, assigned_room)ontooccupied_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))- Vacate: While
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]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]]:
- At
t = 3, bookings0([3, 8)) and1([3, 6)) tie on start time; index0goes first into new room0((8, 0)), and index1opens room1((6, 1)). - At
t = 8, booking2([8, 11)) arrives. Both(6, 1)and(8, 0)satisfyend <= 8and move intoavailable_rooms, which pops the smaller ID0for booking2. - At
t = 9, booking3([9, 12)) arrives while(11, 0)is still busy, pops vacant room1fromavailable_rooms, and yields[0, 1, 0, 1].
Complexity
- Time: O(n log n). Building and sorting the
n(start_time, original_index)pairs takesO(n log n)time. Across the sweep, each of thenbookings is pushed to and popped fromoccupied_roomsat most once, and each freed room ID enters and leavesavailable_roomsat most once per booking; every heap operation costsO(log n)because neither heap ever holds more thannitems. - Space: O(n). Storing
processing_order,result, and both heaps usesO(n)memory even when allnbookings overlap innseparate 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 room0([0, 0, 0, 0]). - Tied start times (
[[5, 8], [1, 5], [5, 6]]): booking1vacates room0att = 5; between bookings0and2starting at5, smaller index0runs first and claims room0, giving[0, 0, 1]. - Identical intervals (
[[1, 5], [1, 5], [1, 5]]): none can share a room, opening rooms0, 1, 2in index order. - Several rooms vacating in reverse ID order (
[[0, 5], [0, 3], [6, 7]]): room1finishes before room0, yet byt = 6both sit inavailable_roomsand room0wins. - Scrambled input order: pairing each start time with
original_indexbefore sorting ensures assignments land at their original positions inresult. - Single booking: opens room
0and returns[0].
Common mistakes
- Using
<instead of<=when releasing rooms: writingoccupied_rooms[0][0] < start_timetreats intervals as closed[start, end]and wastes an extra room on back-to-back bookings. - Using
ifinstead ofwhilewhen releasing rooms: multiple active sessions can finish before the next start time, and popping only one leaves vacant rooms trapped insideoccupied_rooms. - Keeping only one heap: popping directly from
occupied_roomswheneveroccupied_rooms[0][0] <= start_timeminimizes room count, yet overlooks other already-finished rooms that carry a smallerroom_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
meetingswithout original indices: sorting[start, end]pairs loses output positions and breaks start-time ties byendrather thanoriginal_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 inO(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 toO(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_roomsmin-heap with a balanced binary search tree (a sorted tree structure supporting search, insertion, and deletion inO(log R)time) ordered by(room_capacity, room_id), and assign each booking to the tightest free room satisfyingroom_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 size1and2and bookingsA(size1,[0, 2)),B(size1,[1, 10)), andC(size2,[3, 4)), best fit putsAin size1andBin size2, blockingCatt = 3, whereas puttingAin size2andBin size1fits 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 dictionarycurrent_end[room_id], push(new_end, room_id)ontooccupied_roomson an extension, and ignore any popped tuple whereend_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)toO(R)whereRis 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
- What changes are needed when every booking specifies a headcount and each room has a maximum seating limit?
- How can the scheduler handle live meetings that request extra time before they finish?
- How would you architect this allocator as an online service processing an unbounded stream of booking requests?
Similar questions
- Aggregate Category Sales Metrics
- Repeated Uphill Shortest-Path Grid Queries
- Leftmost Longest Pattern Replacement
- Quadtree Compression and Safe Graph Nodes
- Quadtree Compression and 8-Neighbor Grid Word Search
- Single-Vehicle Trip Schedule Feasibility
More Uber interview questions
- Multi-Level Parking Garage Medium
- Optimal Ride-Share Group Size Medium
- Walk Through Your Highest-Impact Engineering Project Medium Pro
- Balanced Prefix Ranges of a Permutation Medium Pro
- First Timestamp Uniting All Target Users Medium Pro
- Locate Grid Robots by Directional Clearances Hard Pro
- Smallest Larger Palindromic Integer Medium Pro
- Locate Grid Robots by Four-Way Obstacle Distances Medium Pro
- Final Exiting Truck on a Single-Track Road Medium Pro
- Highest Path Sum Using Prime-Length Leaps Hard Pro