Object-Oriented Design for a Multi-Floor Garage Allocator
Data Structure DesignModel answerLast updated
Design classes and an allocation API for a multi-floor garage that assigns the closest suitable bay to each vehicle, stays correct under concurrent requests, and handles a full garage.
Multi-Floor Garage Allocator
You are asked to model a garage with several floors. Each floor contains a fixed number of bays in a few sizes (for example motorcycle, compact, large, and accessible). Vehicles arrive and leave at any time, from many threads at once. Your job is to design the classes and the allocation logic.
Requirements
- The garage has multiple floors, and each floor has a limited number of bays of each type.
- A vehicle may only use a bay that is at least as large as the vehicle.
- Provide an operation to park a vehicle and an operation to release a bay.
- Concurrent requests must never assign the same bay to two vehicles.
- Assignment should favor the closest free bay (lower floor first, then lower position on the floor).
- A full garage must be handled gracefully, without crashing.
Classes to define
ParkingLot: owns the floors and performs allocation.ParkingSpot: one bay, with a type, a location, and an occupied/free state.Vehicle: a base type with subclasses such asCar,Truck, andMotorcycle.
Interface
class ParkingLot:
def park_vehicle(self, vehicle: Vehicle) -> Optional[ParkingSpot]:
"""Pick a suitable free bay, mark it occupied, and return it.
Return None if nothing suitable is free."""
def remove_vehicle(self, spot: ParkingSpot) -> None:
"""Mark the bay free so it can be reused."""
Example
A Car asks for a bay. The garage finds the closest free compact bay on the lowest floor, marks it occupied, and returns that ParkingSpot.
What to cover in your answer
- The class design and where each responsibility lives.
- How you find the nearest suitable bay quickly.
- How you guarantee thread safety, and what could go wrong.
- What happens when the garage, or one bay type, is full.
- How easily a new vehicle type could be added.
Hints
Hint 1
Decide who knows what: should the vehicle declare which bay types it can use, or should the garage hard-code that mapping? Think about what happens when a new vehicle type is added.
Hint 2
For fast nearest-bay lookup, keep the free bays for each type in a priority structure ordered by (floor, position) instead of scanning every floor.
Hint 3
For concurrency, think about what must be atomic: removing a bay from the free pool and marking it occupied. Consider using a separate lock per bay type, and what bug appears if the same bay is released twice.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Interviewers usually look for four things: a clean split of responsibilities, a fast nearest-bay lookup, correct concurrency, and graceful handling of a full garage. I would build the design around three decisions.
1. Responsibilities
- Vehicle knows which bay types it can physically use, as an ordered list, smallest fit first.
Motorcycle: motorcycle, compact, largeCar: compact, largeTruck: large- A vehicle with an accessibility permit gets the accessible type placed first, but only if it fits that bay. A truck does not, because accessible bays are car-sized.
- ParkingSpot holds its floor, index, type, and the vehicle currently in it (or
None). - ParkingLot owns allocation. It never checks
isinstanceon vehicles; it just asks for the eligible types. Adding aBusmeans adding one subclass, with no change to the allocator (open/closed principle).
2. Nearest free bay
Keep one min-heap of free bays per bay type, keyed by (floor, index). Popping gives the closest free bay of that type in O(log n) with no floor scanning. Bays are created in sorted order, so each initial list is already a valid heap and construction is O(S).
Across types, try the vehicle's eligible types in order, smallest fit first. This is a deliberate policy: it keeps large bays free for trucks, even if a large bay happens to be closer than a compact one. "Nearest overall" and "best fit" are different goals, so I would state the trade-off and keep the policy in one method so it can be swapped.
3. Concurrency
Use one lock per bay type, guarding that type's heap and the occupancy writes for its bays.
- Popping a bay and assigning the vehicle happen inside the same critical section, so two threads cannot pop the same entry.
park_vehicleholds at most one lock at a time (it releases it before trying the next type), so deadlock is impossible.- Per-type locks mean a motorcycle taking a compact bay does not block a truck looking for a large one. A single global lock is simpler and correct, and is a fine starting answer if I mention the contention cost.
Code sketch
import heapq, threading
from enum import IntEnum
from typing import Optional
class SpotType(IntEnum):
MOTORCYCLE = 0; COMPACT = 1; LARGE = 2; HANDICAPPED = 3
class ParkingLot:
def __init__(self, floors):
self._free = {t: [] for t in SpotType}
self._locks = {t: threading.Lock() for t in SpotType}
self._spots = {}
for f, layout in enumerate(floors):
idx = 0
for t in SpotType:
for _ in range(layout.get(t, 0)):
s = ParkingSpot(f, idx, t)
self._spots[s.spot_id] = s
self._free[t].append((f, idx, s.spot_id))
idx += 1
def park_vehicle(self, vehicle) -> Optional["ParkingSpot"]:
for t in vehicle.eligible_spot_types():
with self._locks[t]:
if self._free[t]:
_, _, sid = heapq.heappop(self._free[t])
spot = self._spots[sid]
spot.vehicle = vehicle
return spot
return None # full: no exception
def remove_vehicle(self, spot) -> None:
if self._spots.get(spot.spot_id) is not spot:
raise ValueError("spot does not belong to this lot")
with self._locks[spot.spot_type]:
if spot.vehicle is None: # already free: idempotent
return
spot.vehicle = None
heapq.heappush(self._free[spot.spot_type],
(spot.floor, spot.index, spot.spot_id))
Why it is correct
- Size rule: a vehicle only ever receives bays from its own eligible list, which contains only large-enough types.
- Invariant: a bay is in its type's heap if and only if it is free. All changes to that invariant happen under the type's lock.
- No double free:
remove_vehiclechecks occupancy under the lock before pushing. Without that check, a duplicate heap entry would later hand one bay to two vehicles. This is the bug candidates miss most often.
Complexity
Let S be the total number of bays and k the number of eligible types (at most 4).
| Operation | Time |
|---|---|
park_vehicle | O(k log S), effectively O(log S) |
remove_vehicle | O(log S) |
| Free count per type | O(1) (heap length) |
| Construction | O(S) |
Space is O(S).
Edge cases and trade-offs
- Full garage or full type: fall through to larger types, then return
None. The caller shows "Full"; an entry gate can read free counts. - Releasing a free bay: no-op, never a duplicate push.
- Releasing a foreign bay: raise
ValueError. - Truck with an accessibility permit: not offered accessible bays.
- Same vehicle parking twice: not prevented here. Add a
plate -> spotmap under its own lock if needed. - Python note: the GIL does not make compound check-then-act sequences atomic, so the locks are still required.
Common mistakes
- Scanning every floor and every bay on each request (
O(S)). - Checking "is free" and then marking occupied in two separate steps without a lock.
- Hard-coding vehicle-to-bay rules inside the garage with
if/elifchains. - Holding several type locks at once in inconsistent order, which risks deadlock.
- Ignoring the policy question of nearest versus best fit.
Follow-ups worth preparing
- Pricing and tickets: a
Ticketobject with entry time and a pluggable fee strategy. - Distributed or multi-gate setups: a shared store with atomic claim operations instead of in-process locks.
- Reservations: a separate state between free and occupied, with expiry.