Design an In-Memory Reservation Manager
Data Structure DesignAuto-graded · 13 test casesLast updated
Implement an in-memory venue reservation system supporting quick seat allocation, cancellation tracking, and capacity queries.
Design an in-memory venue management component that handles real-time seat assignments and reservations across different event halls.
You need to process a sequence of operational commands given by operations along with their corresponding parameters in arguments.
The system should process the following commands:
add_hall: Parameters[hall_id, capacity](wherecapacityis given as a string representation of an integer). Registers a new hall with the specified seat capacity. ReturnsNone.book_seat: Parameters[hall_id, user_id]. Reserves an available seat in the hall. Returns a string representing a unique reservation ID (e.g.,"B1","B2", etc.) if successful. ReturnsNoneif the hall does not exist or has no remaining available seats.cancel_booking: Parameters[booking_id]. Revokes the active reservation. ReturnsTrueif the booking was active and successfully cancelled, orFalseif the reservation ID is invalid or was already cancelled.get_hall_status: Parameters[hall_id]. Returns the count of currently available seats in the specified hall as an integer, orNoneif the hall does not exist.- Unknown command: Returns
None.
Rules & Operational Logic
- Unique booking IDs are formatted as
"B"followed by an incrementing integer counter starting at 1 ("B1","B2","B3", ...). The counter only increments on successful bookings. - Once assigned, counter values are never re-issued or reused, even after a booking is cancelled.
- Seats assigned upon booking must be tracked internally such that allocations and cancellations run in $O(1)$ constant time per operation.
- When a seat is cancelled, its internal seat slot becomes available for future bookings in that hall.
Constraints
- $1 \le \text{len(operations)} \le 10^5$
operationsandargumentshave equal length.hall_id,user_id, andbooking_idstrings consist of alphanumeric characters and underscores.- Total capacity across all registered halls will fit within memory constraints.
Examples
Example 1
Input: booking_system(['add_hall', 'book_seat', 'book_seat', 'book_seat', 'cancel_booking', 'get_hall_status'], [['Hall_A', '2'], ['Hall_A', 'User_1'], ['Hall_A', 'User_2'], ['Hall_A', 'User_3'], ['B1'], ['Hall_A']])
Output: [None, 'B1', 'B2', None, True, 1]
Hints
Hint 1
Use hash maps to map hall IDs to their status and booking IDs to their reservation metadata.
Hint 2
Maintain a stack or list of available seat indices per hall so seat allocation and release take O(1) time.
Hint 3
Ensure the global booking counter increments only when a seat is successfully reserved.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Method Explanation
To achieve constant time $O(1)$ operations for reserving, cancelling, and querying hall capacity, we combine hash maps with stack-based seat pools:
- Hall Map (
halls): Maps eachhall_idto its record:available: A list (acting as a stack) containing free seat identifiers (e.g., indices0tocapacity - 1). Popping from and pushing to the end of a Python list runs in $O(1)$ time.active: A set tracking all currently activebooking_idstrings belonging to the hall.
- Bookings Map (
bookings): Maps each activebooking_idto its details(hall_id, seat_index, user_id). - Sequential Counter (
next_booking_id): An integer starting at 1. Formatted as"B" + str(next_booking_id). It is incremented only when a reservation is successfully completed.
Operational Workflow:
add_hall(hall_id, capacity): Initialize the hall structure with a list of seats[0, ..., capacity - 1].book_seat(hall_id, user_id): Look up the hall. If it doesn't exist oravailableis empty, returnNone. Otherwise, pop a seat fromavailable, generate the ID usingnext_booking_id, store the reservation inbookings, update the hall's active set, increment the counter, and return the booking ID.cancel_booking(booking_id): Perform an atomic removal usingbookings.pop(booking_id, None). If found, retrieve(hall_id, seat_index), remove the booking ID from the hall's active set, pushseat_indexback onto the hall'savailablestack, and returnTrue. If not found, returnFalse.get_hall_status(hall_id): Returnlen(hall["available"])if the hall exists, elseNone.
Complexity Analysis
-
Time Complexity:
add_hall: $O(C)$ where $C$ is the hall capacity (to instantiate seat indices).book_seat: $O(1)$ amortized.cancel_booking: $O(1)$ amortized.get_hall_status: $O(1)$.- Overall Time Complexity: $O(N + \sum C)$ where $N$ is the number of operations and $\sum C$ is the total capacity across all halls.
-
Space Complexity: $O(\sum C + B)$ where $B$ is the maximum number of active bookings at any point.
Python Reference Solution
from typing import List
def booking_system(operations: List[str], arguments: List[List[str]]) -> List[object]:
halls = {}
bookings = {}
results = []
next_booking_id = 1
for op, args in zip(operations, arguments):
if op == "add_hall":
hall_id, capacity_str = args
cap = int(capacity_str)
halls[hall_id] = {
"capacity": cap,
"available": list(range(cap)),
"active": set()
}
results.append(None)
elif op == "book_seat":
hall_id, user_id = args
hall = halls.get(hall_id)
if hall is None or not hall["available"]:
results.append(None)
continue
seat = hall["available"].pop()
booking_id = f"B{next_booking_id}"
next_booking_id += 1
bookings[booking_id] = (hall_id, seat, user_id)
hall["active"].add(booking_id)
results.append(booking_id)
elif op == "cancel_booking":
booking_id = args[0]
booking = bookings.pop(booking_id, None)
if booking is None:
results.append(False)
else:
hall_id, seat, _ = booking
halls[hall_id]["active"].remove(booking_id)
halls[hall_id]["available"].append(seat)
results.append(True)
elif op == "get_hall_status":
hall_id = args[0]
hall = halls.get(hall_id)
if hall is None:
results.append(None)
else:
results.append(len(hall["available"]))
else:
results.append(None)
return results