Multi-Level Parking Garage
Medium · Software Engineering Fundamentals · Software Engineer · Onsite
Problem Statement
Implement a thread-safe object-oriented model for a multi-floor parking garage supporting heterogeneous spot sizes, accessibility permits, best-fit allocation, and nearest-entrance selection:
class SpotType(Enum):
COMPACT = "compact"
LARGE = "large"
HANDICAPPED = "handicapped"
class Vehicle:
size = 0
def __init__(self, plate: str = "", handicapped_permit: bool = False): ...
def allowed_spot_types(self) -> List[SpotType]: ...
class Motorcycle(Vehicle): size = 1
class Car(Vehicle): size = 2
class Truck(Vehicle): size = 3
class ParkingSpot:
def __init__(self, floor: int, number: int, spot_type: SpotType): ...
def is_free(self) -> bool: ...
class ParkingLot:
def __init__(self, layout: List[List[SpotType]]): ...
def park_vehicle(self, vehicle: Vehicle) -> Optional[ParkingSpot]: ...
def remove_vehicle(self, spot: ParkingSpot) -> None: ...
def available_count(self, spot_type: SpotType) -> int: ...
def is_full(self) -> bool: ...
Enforce the following rules across your classes:
- Sizes, capacities, and permits (
Vehicle.allowed_spot_types):- Vehicle sizes are
Motorcycle = 1,Car = 2, andTruck = 3. - Spot capacities are
COMPACT = 2,HANDICAPPED = 2, andLARGE = 3. A vehicle physically fits a spot type whenevercapacity >= vehicle.size. HANDICAPPEDspots may only be used whenvehicle.handicapped_permitisTrueand the vehicle physically fits (size <= 2, so aTrucknever usesHANDICAPPEDeven with a permit).allowed_spot_types()returns eligibleSpotTypevalues in preference order:HANDICAPPEDfirst when permitted and fitting, followed by compatible regular types from tightest to largest (COMPACT, thenLARGE).
- Vehicle sizes are
- Garage layout and nearest-first best-fit allocation (
ParkingLot):layout[f][i]configuresParkingSpot(floor=f, number=i, spot_type=layout[f][i]), where lowerfloorindices are closer to ground level and lowernumberindices are closer to that floor's entrance.park_vehicle(vehicle)checks types invehicle.allowed_spot_types()order across the entire garage. For the first allowedSpotTypethat has at least one free space on any floor, choose the space on the lowestfloor, breaking ties by the lowestnumber. Setspot.vehicle = vehicleand return thatParkingSpot, or returnNoneif no eligible spot is free.
- Vacating spaces and validation (
remove_vehicle):remove_vehicle(spot)clearsspot.vehicle = Noneand returnsspotto the free pool so future calls reuse freed lower-numbered spots first.- Raise
ValueErrorifspotis already free or is not aParkingSpotinstance belonging to thisParkingLot.
- Live capacity queries and concurrency:
available_count(spot_type)returns the total number of free spaces ofspot_typesummed across all floors.is_full()returnsTrueif and only if zero spaces of anySpotTypeare free on any floor.- Every public method on
ParkingLotmust be safe under concurrent calls from multiple threads without double-assigning or corrupting spaces.
Examples
Example 1
Input:
C, L, H = SpotType.COMPACT, SpotType.LARGE, SpotType.HANDICAPPED
lot = ParkingLot([[H, L], [C, C]])
s1 = lot.park_vehicle(Car("NY-101"))
s2 = lot.park_vehicle(Car("NY-202", handicapped_permit=True))
s3 = lot.park_vehicle(Truck("TRK-9"))
free_compact = lot.available_count(C)
full_now = lot.is_full()
Output:
(s1.floor, s1.number, s1.spot_type) == (1, 0, SpotType.COMPACT)
(s2.floor, s2.number, s2.spot_type) == (0, 0, SpotType.HANDICAPPED)
(s3.floor, s3.number, s3.spot_type) == (0, 1, SpotType.LARGE)
free_compact == 1
full_now is False
Explanation: Car("NY-101") prefers [COMPACT, LARGE], so it skips the LARGE space on Floor 0 and claims (1, 0, COMPACT), preserving Floor 0's LARGE space for Truck("TRK-9"). Car("NY-202", handicapped_permit=True) prefers [HANDICAPPED, COMPACT, LARGE] and claims (0, 0, HANDICAPPED). Spot (1, 1, COMPACT) remains open.
Example 2
Input:
C = SpotType.COMPACT
lot = ParkingLot([[C, C]])
first = lot.park_vehicle(Motorcycle("M-1"))
second = lot.park_vehicle(Car("C-2"))
overflow = lot.park_vehicle(Car("C-3"))
lot.remove_vehicle(first)
reclaimed = lot.park_vehicle(Car("C-3"))
Output:
(first.floor, first.number) == (0, 0)
(second.floor, second.number) == (0, 1)
overflow is None
reclaimed is first and (reclaimed.floor, reclaimed.number) == (0, 0)
Explanation: M-1 and C-2 fill (0, 0) and (0, 1), so C-3 initially receives None. Once first at (0, 0) is freed, parking C-3 immediately reassigns (0, 0).
Constraints
- Avoid scanning occupied spaces linearly inside the lock; retrieving or returning a spot on a floor with
sspots should run inO(log s)time so concurrent gates do not bottleneck when the garage is nearly full. - Calling
remove_vehicletwice on the same vacated spot, or passing aParkingSpotcreated externally or by anotherParkingLot, must raiseValueErrorwithout mutating garage state.
Step-by-step walkthrough
Clarify the rules and tie-breakers
Before writing any classes, we need to pin down three practical rules so our code never has to guess:
- Physical size compatibility: Give each vehicle a numeric
size(Motorcycle = 1,Car = 2,Truck = 3) and each spot type acapacity(COMPACT = 2,HANDICAPPED = 2,LARGE = 3). A vehicle physically fits a spot whenevercapacity >= size. - Permit rule for reserved spots:
HANDICAPPEDis a car-sized spot (capacity = 2) reserved exclusively for vehicles withhandicapped_permit=True. Permit holders whose vehicle physically fits tryHANDICAPPEDfirst; a truck with a permit (size = 3) still cannot squeeze into a car-sized spot, and drivers without a permit may never useHANDICAPPED. - Best-fit first, nearest second: Suppose a
Carenters when Floor 0 has aLARGEspot near the gate and Floor 1 has aCOMPACTspot. If cars grabbedLARGEspots first, trucks would soon be turned away whileCOMPACTspots sat empty! So a vehicle always tries its smallest compatible regular type (COMPACTbeforeLARGE) across the lot first, and within that type picks the lowest floor, then the lowest spot number (closest to the entrance).
Vehicle Size Spot preference order (allowed_spot_types) ---------------------------------------------------------------------------- Motorcycle() 1 [COMPACT, LARGE] Car() 2 [COMPACT, LARGE] Truck() 3 [LARGE] Motorcycle(permit=True) 1 [HANDICAPPED, COMPACT, LARGE] Car(permit=True) 2 [HANDICAPPED, COMPACT, LARGE] Truck(permit=True) 3 [LARGE] (size 3 > HANDICAPPED capacity 2)When no compatible spot is free,
park_vehiclereturnsNoneinstead of crashing—a full lot is a normal everyday state. In contrast, callingremove_vehicleon a spot that is already empty or belongs to a differentParkingLotindicates a caller bug, so it raisesValueError.- Physical size compatibility: Give each vehicle a numeric
Model vehicles without `isinstance` chains
A common beginner trap is putting a long
if isinstance(vehicle, Truck): ... elif isinstance(vehicle, Car): ...chain insideParkingLot. That means adding a newVanclass later forces you to editParkingLottoo.Instead, keep spot capacities in one dictionary (
SPOT_CAPACITY) and putallowed_spot_types()on theVehiclebase class. Each subclass only declares itssize. Adding a new vehicle size is a two-line subclass, and if a special vehicle (like an electric car) ever needs custom logic, it can overrideallowed_spot_types()without touchingParkingLot.class SpotType(Enum): COMPACT = "compact" LARGE = "large" HANDICAPPED = "handicapped" # Maximum vehicle size each spot type can fit (1 = motorcycle, 2 = car, 3 = truck). SPOT_CAPACITY: Dict[SpotType, int] = { SpotType.COMPACT: 2, SpotType.HANDICAPPED: 2, SpotType.LARGE: 3, } # Non-reserved spot types ordered from smallest to largest so vehicles try tightest fit first. REGULAR_TYPES_BY_SIZE: List[SpotType] = [SpotType.COMPACT, SpotType.LARGE] class Vehicle: """Base class for vehicles. Subclasses set `size`; eligibility rules live here.""" size = 0 def __init__(self, plate: str = "", handicapped_permit: bool = False): self.plate = plate self.handicapped_permit = handicapped_permit def fits(self, spot_type: SpotType) -> bool: # Use >= because a vehicle can park in an exact-size spot or any larger spot. return SPOT_CAPACITY[spot_type] >= self.size def allowed_spot_types(self) -> List[SpotType]: """Spot types this vehicle may occupy, ordered from most preferred to least.""" allowed: List[SpotType] = [] # Phase 1: Permit holders try HANDICAPPED first, provided the vehicle physically fits # (a Truck with a permit has size 3 > capacity 2, so it still cannot use HANDICAPPED). if self.handicapped_permit and self.fits(SpotType.HANDICAPPED): allowed.append(SpotType.HANDICAPPED) # Phase 2: Everyone tries regular types from smallest to largest (best-fit policy) # so small vehicles do not consume LARGE spots while COMPACT spots remain open. for spot_type in REGULAR_TYPES_BY_SIZE: if self.fits(spot_type): allowed.append(spot_type) return allowed class Motorcycle(Vehicle): size = 1 class Car(Vehicle): size = 2 class Truck(Vehicle): size = 3Why scanning every spot is too slow under concurrency
The simplest implementation of
park_vehicleloops over each allowedSpotType, loops over each floor, and scans every spot from0tos - 1until it finds a free one.While easy to write, scanning costs
O(S)time per car forStotal spots. Worse, in a multi-threaded parking garage, that scan must run while holding a lock so two entry gates do not claim the same spot. When a 5,000-spot garage is 99% full, every arriving car scans almost all 5,000 spots before finding an open space near the end, making every other gate wait in line.Key idea: one min-heap of free spot numbers per floor and type
Instead of searching through occupied spots, we only want to track free spots—and always grab the one with the smallest spot number (closest to the entrance).
A min-heap (a binary tree stored in a flat Python list where the smallest item always sits at index
0) gives us exact nearest-spot lookup: - Pop nearest free spot:heapq.heappop(heap)removes and returns the smallest free spot number inO(log s)time (wheresis the number of spots on that floor). - Return a freed spot:heapq.heappush(heap, spot.number)puts the spot number back inO(log s)time. - Check availability:len(heap)tells us how many free spots of that type exist on this floor inO(1)time.Why not a Python
setor a first-in-first-outQueue? Asetpops an arbitrary spot, and a FIFOQueuehands out whichever spot was vacated longest ago—neither guarantees the spot closest to the entrance!Floor 0 layout: [0: HANDICAPPED, 1: COMPACT, 2: COMPACT, 3: LARGE, 4: COMPACT] Initial free_heaps on Floor 0: HANDICAPPED -> [0] COMPACT -> [1, 2, 4] <-- smallest free number (1) is always at index 0 LARGE -> [3]Notice a neat initialization property: when we build a floor by iterating
number = 0, 1, 2, ..., we append numbers in strictly increasing order. Because every sorted list already satisfies the min-heap rule (heap[i] <= heap[2*i + 1]andheap[i] <= heap[2*i + 2]), each list starts as a valid min-heap inO(s)time without even callingheapq.heapify!class ParkingSpot: """One physical parking space. Lower `number` means closer to the floor entrance.""" def __init__(self, floor: int, number: int, spot_type: SpotType): self.floor = floor self.number = number self.spot_type = spot_type self.vehicle: Optional[Vehicle] = None def is_free(self) -> bool: return self.vehicle is None def __repr__(self) -> str: status = "free" if self.is_free() else "occupied" return f"ParkingSpot(floor={self.floor}, number={self.number}, {self.spot_type.name}, {status})" class ParkingFloor: """Manages all spots on a single floor and fast lookup of the nearest free spot per type.""" def __init__(self, level: int, layout: List[SpotType]): self.level = level # self.spots: [ParkingSpot(level, 0, ...), ParkingSpot(level, 1, ...), ...] indexed by spot number. self.spots: List[ParkingSpot] = [] # self.free_heaps: {SpotType.COMPACT: [1, 4], SpotType.LARGE: [3], ...} # Each list is a min-heap of free spot numbers, keeping the smallest (nearest) number at index 0. self.free_heaps: Dict[SpotType, List[int]] = {} for spot_type in SpotType: self.free_heaps[spot_type] = [] for number, spot_type in enumerate(layout): spot = ParkingSpot(level, number, spot_type) self.spots.append(spot) # Spot numbers arrive in strictly increasing order (0, 1, 2, ...), and any sorted # list already obeys the min-heap rule (parent <= children), so no heapify is needed. self.free_heaps[spot_type].append(number) def take_nearest(self, spot_type: SpotType) -> Optional[ParkingSpot]: heap = self.free_heaps[spot_type] if not heap: return None # Pop the smallest free spot number so the driver gets the spot closest to the entrance. nearest_number = heapq.heappop(heap) return self.spots[nearest_number] def give_back(self, spot: ParkingSpot) -> None: # Push the freed spot number back into its type's min-heap in O(log s) time. heapq.heappush(self.free_heaps[spot.spot_type], spot.number) def free_count(self, spot_type: SpotType) -> int: return len(self.free_heaps[spot_type])Coordinate floors and validate removals in `ParkingLot`
ParkingLotconnects the floors together: -park_vehicle(vehicle)loops overvehicle.allowed_spot_types()on the outside (enforcing best-fit first) andself.floorsfrom0upward on the inside (enforcing lowest floor first). As soon asfloor.take_nearest(spot_type)returns a spot, we setspot.vehicle = vehicleand return it. -remove_vehicle(spot)must validate two things before mutating anything: 1. Ownership (_owns): Checkfloor.spots[spot.number] is spotusing Python'sisidentity operator, not just==on coordinates. Otherwise aParkingSpot(0, 0, COMPACT)created in a differentParkingLotwould pass coordinate checks and corrupt our heap! 2. Not already free: Ifspot.is_free()is alreadyTrue, pushingspot.numberinto the min-heap again would put the number in the heap twice, causing the next two cars to be assigned the exact same physical space.Thread safety: why check-then-act needs a lock
Both
park_vehicleandremove_vehicleare check-then-act sequences (first inspect state, then modify state). Without a mutex lock (threading.Lock, which lets only one thread enter awith self._lock:block at a time), two threads freeing or claiming a spot can interleave midway through:Without a lock (two threads accidentally call remove_vehicle on spot 7): Thread A: spot.is_free() -> False Thread B: spot.is_free() -> False Thread A: spot.vehicle = None Thread A: heappush(free_heap, 7) Thread B: spot.vehicle = None Thread B: heappush(free_heap, 7) Result: free_heap now holds [7, 7] -> the next two arriving cars BOTH receive spot 7!Even in standard CPython, the runtime's internal GIL (Global Interpreter Lock) can switch threads between any two bytecode instructions, so multi-step Python methods are never atomic by themselves. Wrapping each public method in
with self._lock:makes the entire check-and-update indivisible. Because each critical section only checks at most3 * Fheap lengths and performs a singleO(log s)heap operation (taking a few microseconds), one lot-wide lock is fast, simple, and completely immune to deadlocks.Trace a concrete sequence of operations
Let's trace
layout = [[H, L], [C, C]]step by step:Initial state: Floor 0 free_heaps: H=[0], C=[], L=[1] Floor 1 free_heaps: H=[], C=[0, 1], L=[] 1. car1 = Car("NY-101") -> allowed [C, L] - Try C: Floor 0 empty, Floor 1 pops 0 -> Spot(1, 0, COMPACT) marked occupied. - Floor 1 heaps now: H=[], C=[1], L=[] 2. car2 = Car("NY-202", handicapped_permit=True) -> allowed [H, C, L] - Try H on Floor 0: pop 0 -> Spot(0, 0, HANDICAPPED) marked occupied. - Floor 0 heaps now: H=[], C=[], L=[1] 3. rig = Truck("TRK-9") -> allowed [L] - Try L on Floor 0: pop 1 -> Spot(0, 1, LARGE) marked occupied. - Floor 0 heaps now: H=[], C=[], L=[] 4. remove_vehicle(Spot(1, 0, COMPACT)) - Owned by this lot and currently occupied -> spot.vehicle = None, push 0 into Floor 1 C-heap. - Floor 1 heaps now: H=[], C=[0, 1], L=[] (0 returns to the top of the min-heap!)When the next
Car()arrives,heappopon Floor 1'sCOMPACTheap immediately hands back spot0because0 < 1.Complete solution
from typing import Dict, List, Optional import heapq import threading from enum import Enum class SpotType(Enum): COMPACT = "compact" LARGE = "large" HANDICAPPED = "handicapped" # Maximum vehicle size each spot type can fit (1 = motorcycle, 2 = car, 3 = truck). SPOT_CAPACITY: Dict[SpotType, int] = { SpotType.COMPACT: 2, SpotType.HANDICAPPED: 2, SpotType.LARGE: 3, } # Non-reserved spot types ordered from smallest to largest so vehicles try tightest fit first. REGULAR_TYPES_BY_SIZE: List[SpotType] = [SpotType.COMPACT, SpotType.LARGE] class Vehicle: """Base class for vehicles. Subclasses set `size`; eligibility rules live here.""" size = 0 def __init__(self, plate: str = "", handicapped_permit: bool = False): self.plate = plate self.handicapped_permit = handicapped_permit def fits(self, spot_type: SpotType) -> bool: # Use >= because a vehicle can park in an exact-size spot or any larger spot. return SPOT_CAPACITY[spot_type] >= self.size def allowed_spot_types(self) -> List[SpotType]: """Spot types this vehicle may occupy, ordered from most preferred to least.""" allowed: List[SpotType] = [] # Phase 1: Permit holders try HANDICAPPED first, provided the vehicle physically fits # (a Truck with a permit has size 3 > capacity 2, so it still cannot use HANDICAPPED). if self.handicapped_permit and self.fits(SpotType.HANDICAPPED): allowed.append(SpotType.HANDICAPPED) # Phase 2: Everyone tries regular types from smallest to largest (best-fit policy) # so small vehicles do not consume LARGE spots while COMPACT spots remain open. for spot_type in REGULAR_TYPES_BY_SIZE: if self.fits(spot_type): allowed.append(spot_type) return allowed class Motorcycle(Vehicle): size = 1 class Car(Vehicle): size = 2 class Truck(Vehicle): size = 3 class ParkingSpot: """One physical parking space. Lower `number` means closer to the floor entrance.""" def __init__(self, floor: int, number: int, spot_type: SpotType): self.floor = floor self.number = number self.spot_type = spot_type self.vehicle: Optional[Vehicle] = None def is_free(self) -> bool: return self.vehicle is None def __repr__(self) -> str: status = "free" if self.is_free() else "occupied" return f"ParkingSpot(floor={self.floor}, number={self.number}, {self.spot_type.name}, {status})" class ParkingFloor: """Manages all spots on a single floor and fast lookup of the nearest free spot per type.""" def __init__(self, level: int, layout: List[SpotType]): self.level = level # self.spots: [ParkingSpot(level, 0, ...), ParkingSpot(level, 1, ...), ...] indexed by spot number. self.spots: List[ParkingSpot] = [] # self.free_heaps: {SpotType.COMPACT: [1, 4], SpotType.LARGE: [3], ...} # Each list is a min-heap of free spot numbers, keeping the smallest (nearest) number at index 0. self.free_heaps: Dict[SpotType, List[int]] = {} for spot_type in SpotType: self.free_heaps[spot_type] = [] for number, spot_type in enumerate(layout): spot = ParkingSpot(level, number, spot_type) self.spots.append(spot) # Spot numbers arrive in strictly increasing order (0, 1, 2, ...), and any sorted # list already obeys the min-heap rule (parent <= children), so no heapify is needed. self.free_heaps[spot_type].append(number) def take_nearest(self, spot_type: SpotType) -> Optional[ParkingSpot]: heap = self.free_heaps[spot_type] if not heap: return None # Pop the smallest free spot number so the driver gets the spot closest to the entrance. nearest_number = heapq.heappop(heap) return self.spots[nearest_number] def give_back(self, spot: ParkingSpot) -> None: # Push the freed spot number back into its type's min-heap in O(log s) time. heapq.heappush(self.free_heaps[spot.spot_type], spot.number) def free_count(self, spot_type: SpotType) -> int: return len(self.free_heaps[spot_type]) class ParkingLot: """Thread-safe multi-floor parking lot entry point.""" def __init__(self, layout: List[List[SpotType]]): # self.floors: [ParkingFloor(0, ...), ParkingFloor(1, ...), ...] from ground floor upward. self.floors: List[ParkingFloor] = [] for level, floor_layout in enumerate(layout): self.floors.append(ParkingFloor(level, floor_layout)) # Single mutex lock protecting all check-then-act state changes across floors and spots. self._lock = threading.Lock() def park_vehicle(self, vehicle: Vehicle) -> Optional[ParkingSpot]: """Assign the best-fitting, nearest available spot, or return None if none fits.""" with self._lock: # Outer loop over allowed spot types enforces best-fit first (e.g., COMPACT before LARGE). # Inner loop over floors from 0 upward picks the lowest floor, then the heap picks the lowest number. for spot_type in vehicle.allowed_spot_types(): for floor in self.floors: spot = floor.take_nearest(spot_type) if spot is not None: spot.vehicle = vehicle return spot return None def remove_vehicle(self, spot: ParkingSpot) -> None: """Free an occupied spot belonging to this lot, or raise ValueError.""" with self._lock: if not self._owns(spot): raise ValueError(f"{spot} does not belong to this parking lot") # Reject double-freeing: pushing a free spot's number into the min-heap a second time # would create duplicate entries and later assign the same physical spot to two vehicles. if spot.is_free(): raise ValueError(f"{spot} is already free") spot.vehicle = None self.floors[spot.floor].give_back(spot) def available_count(self, spot_type: SpotType) -> int: """Total number of free spots of `spot_type` across all floors.""" with self._lock: total_free = 0 for floor in self.floors: total_free += floor.free_count(spot_type) return total_free def is_full(self) -> bool: """True only when zero spots of any type are free on any floor.""" with self._lock: for floor in self.floors: for spot_type in SpotType: if floor.free_count(spot_type) > 0: return False return True def _owns(self, spot: ParkingSpot) -> bool: if not isinstance(spot, ParkingSpot): return False if not (0 <= spot.floor < len(self.floors)): return False floor = self.floors[spot.floor] if not (0 <= spot.number < len(floor.spots)): return False # Check object identity (`is`), not just coordinates, so a spot from a different # ParkingLot instance with the same (floor, number) is still rejected. return floor.spots[spot.number] is spot✅ Submit now — all tests should pass.
Intuition & how it works
Think of a restaurant host stand that keeps separate clipboards of open tables grouped by table size (2-top, 4-top, accessible booth) on each floor, always sorted with the table closest to the front door on top. When a party of two walks in, the host checks the 2-top clipboard first so big 4-top tables stay open for larger groups, pops the closest open table number off the top, and writes the number back in sorted position when the guests leave.
The naive approach—walking down every aisle on every floor from spot 0 to the end whenever a car arrives—is too slow and stalls concurrent gates. In a 3,000-spot garage that is nearly full, every incoming car would inspect thousands of occupied spots while holding a lock, forcing all other entry and exit gates to wait. Worse, using an unordered set or a first-in-first-out queue would be fast, but would assign random or back-corner spots instead of the space nearest the entrance.
Instead, each floor maintains one min-heap (a binary tree stored in a list that always keeps its smallest number at index 0 and supports pop/push in logarithmic time) of free spot numbers per SpotType, protected by a mutex lock (a synchronization primitive that allows only one thread inside a critical code block at a time). Trace a 2-floor garage [[HANDICAPPED, LARGE], [COMPACT, COMPACT]]:
1. Initially, Floor 0 holds heaps HANDICAPPED: [0], LARGE: [1] and Floor 1 holds COMPACT: [0, 1].
2. Car("NY-101") arrives (allowed = [COMPACT, LARGE]): it checks COMPACT across all floors first, pops 0 from Floor 1's [0, 1], and leaves Floor 0's LARGE spot safe for a Truck.
3. Car("NY-202", handicapped_permit=True) arrives (allowed = [HANDICAPPED, COMPACT, LARGE]): pops 0 from Floor 0's HANDICAPPED heap, and Truck("TRK-9") then claims (0, 1, LARGE).
4. When Car("NY-101") vacates (1, 0), 0 is pushed back onto Floor 1's COMPACT heap [0, 1], ready to be assigned ahead of 1 to the next compact vehicle.
Complexity
- Initialization (
__init__):O(S)time andO(S)space, whereSis the total number of spots across all floors. We visit each spot once in increasing index order (0, 1, 2, ...), which produces valid sorted min-heaps immediately without needing an extra heap-building pass. park_vehicle:O(T * F + log s)time, whereT <= 3is the number of allowed spot types,Fis the number of floors, andsis the maximum number of spots on a single floor. Checking an empty heap on a floor takesO(1)time, and as soon as we find the first non-empty heap, we perform a singleO(log s)heap pop.remove_vehicle:O(log s)time, because verifying ownership via list indexing takesO(1)time and pushing the freed spot number back into its floor's min-heap takesO(log s)time.available_countandis_full:O(F)andO(F * T)time respectively, because we sum or checklen(heap)(O(1)per heap) across theFfloors. (Maintaining lot-level integer counters perSpotTypewould make bothO(1)if queried at very high frequency.)- Space:
O(S)memory total, because each of theSspots is stored once as aParkingSpotobject and appears at most once as an integer in its floor's min-heap when free.
Edge cases
- Lot full or full for a specific vehicle:
park_vehiclereturnsNonecleanly instead of raising an exception. Note that a lot can returnNonefor aTruckwhen allLARGEspots are full even whileCOMPACTspots remain free andis_full()isFalse. - Only
HANDICAPPEDspots left: A vehicle withouthandicapped_permit=True(or aTruckeven withhandicapped_permit=True, sincesize 3 > capacity 2) receivesNonewhileis_full()correctly reportsFalse. - Double-freeing an already empty spot: Raises
ValueErrorbefore touching the heap. Allowing a secondheappushwould duplicate the spot number inside the min-heap and cause two future cars to be assigned the same spot. - Foreign or fabricated
ParkingSpotobjects:_ownschecks object identity (floor.spots[spot.number] is spot), not just coordinate bounds, so passingParkingSpot(0, 0, COMPACT)from a secondParkingLotinstance properly raisesValueError. - Empty lot or empty floors (
[]or[[], [COMPACT]]): Handled naturally—empty floors simply have empty heaps, andParkingLot([]).is_full()returnsTrue.
Common mistakes
- Nearest-first before best-fit: Picking the closest spot of any compatible size lets motorcycles and compact cars consume ground-floor
LARGEspots, stranding trucks whileCOMPACTspots sit empty upstairs. - Splitting check and update across the lock: Finding a free spot inside
with self._lock:, releasing the lock, and settingspot.vehicle = vehicleoutside creates a race condition (a bug where outcome depends on unpredictable thread timing) in which two threads modify the same spot. - Assuming Python's GIL makes methods thread-safe: The GIL (Global Interpreter Lock) is CPython's internal interpreter lock, and it can switch threads between any two bytecode lines inside a method (and does not exist in free-threaded Python builds). You still need an explicit
threading.Lock. - Using a
setor FIFOQueuefor free spots: Both giveO(1)insert/remove, but neither returns the smallest spot number, breaking the "nearest available spot" requirement. - Hardcoding
if isinstance(vehicle, ...)insideParkingLot: Putting vehicle-to-spot compatibility insideParkingLotviolates separation of concerns and forces edits to the lot class whenever a new vehicle type is introduced.
Alternative approaches
- One lot-wide min-heap per
SpotTypestoring(floor, number)tuples: Eliminates theO(F)floor scan sopark_vehicleruns inO(T + log S)time even for dozens of floors, at the minor cost of storing 2-tuples inParkingLotinstead of keeping each floor self-contained. - Per-floor locks instead of one lot-wide lock: Increases concurrency if thousands of gates hit different floors simultaneously. Locking one floor at a time (
for floor in self.floors: with floor.lock: ...) avoids deadlocks and never double-assigns a spot, though a spot freed on Floor 0 just after a thread moved on to Floor 1 might be missed on that single pass. - Bitset per floor and type: Represent free spots as bits in an integer (
1= free,0= occupied) and find the lowest set bit withbits & -bitsinO(1)word operations—compact when persisting state in memory caches.
Follow-up questions
- How would you extend the object model to allow drivers to pre-book spaces for a future time window? Add a
Reservation(id, spot, start_time, end_time, plate)record and store a sorted list of booked[start_time, end_time)intervals per spot, using binary search (bisect, which locates insertion positions in a sorted list inO(log k)time) under the lock to verify zero overlap before confirming a booking. For walk-in drivers without reservations, either partition a dedicated pool of walk-in spots or only assign spots whose next reservation starts after a posted maximum stay, and release unclaimed reservations after a grace window (such as 15 minutes) using an idempotency key (a unique client-generated request token so network retries never create duplicate reservations). - How would the architecture evolve if capacity had to be managed across dozens of separate garage buildings? Partition (shard, meaning split data ownership across independent servers so each server owns a disjoint subset) the system by
building_id, giving each building its own allocation service and relational database. Inside one building, claiming a spot uses an atomic database row update (UPDATE spots SET vehicle_plate = :plate WHERE spot_id = :id AND vehicle_plate IS NULL) so two gates can never double-book a space even across server restarts. A lightweight routing gateway can direct drivers toward buildings with open capacity using cached counts that refresh every few seconds—slightly stale routing counts are harmless because the target building's database still enforces strict single-assignment. - Where would you plug in exit billing that charges drivers according to vehicle class and parked duration? Issue a
Ticket(ticket_id, vehicle, spot, entry_time)whenpark_vehiclesucceeds, inject aPricingStrategy(such as hourly tiers per vehicle class stored in integer cents to avoid floating-point rounding bugs), and inject aPaymentProcessorinterface for charging at exit. Crucially, perform the slow external payment network call outsideself._lock(marking the ticket aspayingfirst so it cannot be billed twice) so a 3-second credit-card terminal never freezes other entry and exit gates, and callremove_vehicleto free the spot only after payment succeeds.
Follow-up questions
- How would you extend the object model to allow drivers to pre-book spaces for a future time window?
- How would the architecture evolve if capacity had to be managed across dozens of separate garage buildings?
- Where would you plug in exit billing that charges drivers according to vehicle class and parked duration?
Similar questions
- In-Memory Room Booking Scheduler
- Multi-Floor Garage Allocation and Billing
- Time-Windowed In-Memory Event Counter
- Iterative Directory Tree with Explicit-Stack File Lookup
- Object-Oriented Multi-Level Parking Garage Model
- Directed Social Graph Relationships
More Uber interview questions
- Optimal Ride-Share Group Size Medium
- Deterministic Room Allocation for Intervals 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