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:

  1. Sizes, capacities, and permits (Vehicle.allowed_spot_types):
    • Vehicle sizes are Motorcycle = 1, Car = 2, and Truck = 3.
    • Spot capacities are COMPACT = 2, HANDICAPPED = 2, and LARGE = 3. A vehicle physically fits a spot type whenever capacity >= vehicle.size.
    • HANDICAPPED spots may only be used when vehicle.handicapped_permit is True and the vehicle physically fits (size <= 2, so a Truck never uses HANDICAPPED even with a permit).
    • allowed_spot_types() returns eligible SpotType values in preference order: HANDICAPPED first when permitted and fitting, followed by compatible regular types from tightest to largest (COMPACT, then LARGE).
  2. Garage layout and nearest-first best-fit allocation (ParkingLot):
    • layout[f][i] configures ParkingSpot(floor=f, number=i, spot_type=layout[f][i]), where lower floor indices are closer to ground level and lower number indices are closer to that floor's entrance.
    • park_vehicle(vehicle) checks types in vehicle.allowed_spot_types() order across the entire garage. For the first allowed SpotType that has at least one free space on any floor, choose the space on the lowest floor, breaking ties by the lowest number. Set spot.vehicle = vehicle and return that ParkingSpot, or return None if no eligible spot is free.
  3. Vacating spaces and validation (remove_vehicle):
    • remove_vehicle(spot) clears spot.vehicle = None and returns spot to the free pool so future calls reuse freed lower-numbered spots first.
    • Raise ValueError if spot is already free or is not a ParkingSpot instance belonging to this ParkingLot.
  4. Live capacity queries and concurrency:
    • available_count(spot_type) returns the total number of free spaces of spot_type summed across all floors.
    • is_full() returns True if and only if zero spaces of any SpotType are free on any floor.
    • Every public method on ParkingLot must 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 s spots should run in O(log s) time so concurrent gates do not bottleneck when the garage is nearly full.
  • Calling remove_vehicle twice on the same vacated spot, or passing a ParkingSpot created externally or by another ParkingLot, must raise ValueError without mutating garage state.

Step-by-step walkthrough

  1. 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:

    1. Physical size compatibility: Give each vehicle a numeric size (Motorcycle = 1, Car = 2, Truck = 3) and each spot type a capacity (COMPACT = 2, HANDICAPPED = 2, LARGE = 3). A vehicle physically fits a spot whenever capacity >= size.
    2. Permit rule for reserved spots: HANDICAPPED is a car-sized spot (capacity = 2) reserved exclusively for vehicles with handicapped_permit=True. Permit holders whose vehicle physically fits try HANDICAPPED first; a truck with a permit (size = 3) still cannot squeeze into a car-sized spot, and drivers without a permit may never use HANDICAPPED.
    3. Best-fit first, nearest second: Suppose a Car enters when Floor 0 has a LARGE spot near the gate and Floor 1 has a COMPACT spot. If cars grabbed LARGE spots first, trucks would soon be turned away while COMPACT spots sat empty! So a vehicle always tries its smallest compatible regular type (COMPACT before LARGE) 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_vehicle returns None instead of crashing—a full lot is a normal everyday state. In contrast, calling remove_vehicle on a spot that is already empty or belongs to a different ParkingLot indicates a caller bug, so it raises ValueError.

  2. Model vehicles without `isinstance` chains

    A common beginner trap is putting a long if isinstance(vehicle, Truck): ... elif isinstance(vehicle, Car): ... chain inside ParkingLot. That means adding a new Van class later forces you to edit ParkingLot too.

    Instead, keep spot capacities in one dictionary (SPOT_CAPACITY) and put allowed_spot_types() on the Vehicle base class. Each subclass only declares its size. 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 override allowed_spot_types() without touching ParkingLot.

    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
    
  3. Why scanning every spot is too slow under concurrency

    The simplest implementation of park_vehicle loops over each allowed SpotType, loops over each floor, and scans every spot from 0 to s - 1 until it finds a free one.

    While easy to write, scanning costs O(S) time per car for S total 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.

  4. 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 in O(log s) time (where s is the number of spots on that floor). - Return a freed spot: heapq.heappush(heap, spot.number) puts the spot number back in O(log s) time. - Check availability: len(heap) tells us how many free spots of that type exist on this floor in O(1) time.

    Why not a Python set or a first-in-first-out Queue? A set pops an arbitrary spot, and a FIFO Queue hands 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] and heap[i] <= heap[2*i + 2]), each list starts as a valid min-heap in O(s) time without even calling heapq.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])
    
  5. Coordinate floors and validate removals in `ParkingLot`

    ParkingLot connects the floors together: - park_vehicle(vehicle) loops over vehicle.allowed_spot_types() on the outside (enforcing best-fit first) and self.floors from 0 upward on the inside (enforcing lowest floor first). As soon as floor.take_nearest(spot_type) returns a spot, we set spot.vehicle = vehicle and return it. - remove_vehicle(spot) must validate two things before mutating anything: 1. Ownership (_owns): Check floor.spots[spot.number] is spot using Python's is identity operator, not just == on coordinates. Otherwise a ParkingSpot(0, 0, COMPACT) created in a different ParkingLot would pass coordinate checks and corrupt our heap! 2. Not already free: If spot.is_free() is already True, pushing spot.number into 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.

  6. Thread safety: why check-then-act needs a lock

    Both park_vehicle and remove_vehicle are check-then-act sequences (first inspect state, then modify state). Without a mutex lock (threading.Lock, which lets only one thread enter a with 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 most 3 * F heap lengths and performs a single O(log s) heap operation (taking a few microseconds), one lot-wide lock is fast, simple, and completely immune to deadlocks.

  7. 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, heappop on Floor 1's COMPACT heap immediately hands back spot 0 because 0 < 1.

  8. 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 and O(S) space, where S is 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, where T <= 3 is the number of allowed spot types, F is the number of floors, and s is the maximum number of spots on a single floor. Checking an empty heap on a floor takes O(1) time, and as soon as we find the first non-empty heap, we perform a single O(log s) heap pop.
  • remove_vehicle: O(log s) time, because verifying ownership via list indexing takes O(1) time and pushing the freed spot number back into its floor's min-heap takes O(log s) time.
  • available_count and is_full: O(F) and O(F * T) time respectively, because we sum or check len(heap) (O(1) per heap) across the F floors. (Maintaining lot-level integer counters per SpotType would make both O(1) if queried at very high frequency.)
  • Space: O(S) memory total, because each of the S spots is stored once as a ParkingSpot object 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_vehicle returns None cleanly instead of raising an exception. Note that a lot can return None for a Truck when all LARGE spots are full even while COMPACT spots remain free and is_full() is False.
  • Only HANDICAPPED spots left: A vehicle without handicapped_permit=True (or a Truck even with handicapped_permit=True, since size 3 > capacity 2) receives None while is_full() correctly reports False.
  • Double-freeing an already empty spot: Raises ValueError before touching the heap. Allowing a second heappush would duplicate the spot number inside the min-heap and cause two future cars to be assigned the same spot.
  • Foreign or fabricated ParkingSpot objects: _owns checks object identity (floor.spots[spot.number] is spot), not just coordinate bounds, so passing ParkingSpot(0, 0, COMPACT) from a second ParkingLot instance properly raises ValueError.
  • Empty lot or empty floors ([] or [[], [COMPACT]]): Handled naturally—empty floors simply have empty heaps, and ParkingLot([]).is_full() returns True.

Common mistakes

  • Nearest-first before best-fit: Picking the closest spot of any compatible size lets motorcycles and compact cars consume ground-floor LARGE spots, stranding trucks while COMPACT spots sit empty upstairs.
  • Splitting check and update across the lock: Finding a free spot inside with self._lock:, releasing the lock, and setting spot.vehicle = vehicle outside 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 set or FIFO Queue for free spots: Both give O(1) insert/remove, but neither returns the smallest spot number, breaking the "nearest available spot" requirement.
  • Hardcoding if isinstance(vehicle, ...) inside ParkingLot: Putting vehicle-to-spot compatibility inside ParkingLot violates 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 SpotType storing (floor, number) tuples: Eliminates the O(F) floor scan so park_vehicle runs in O(T + log S) time even for dozens of floors, at the minor cost of storing 2-tuples in ParkingLot instead 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 with bits & -bits in O(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 in O(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) when park_vehicle succeeds, inject a PricingStrategy (such as hourly tiers per vehicle class stored in integer cents to avoid floating-point rounding bugs), and inject a PaymentProcessor interface for charging at exit. Crucially, perform the slow external payment network call outside self._lock (marking the ticket as paying first so it cannot be billed twice) so a 3-second credit-card terminal never freezes other entry and exit gates, and call remove_vehicle to free the spot only after payment succeeds.

Follow-up questions

Similar questions

More Uber interview questions

All 217 Uber questions →