Multi-Level Parking Facility: Class Structure and Operations
Data Structure DesignModel answerLast updated
Model a parking facility with levels and sized spots, supporting vehicle entry/exit, spot allocation by compatibility, and availability queries.
You need to create an object-oriented model for managing a multi-level parking facility.
System Requirements:
The facility consists of multiple floors, where each floor contains a collection of parking spots. Spots come in three sizes: small, medium, and large. Vehicles arrive in different forms—motorcycles, cars, and buses/trucks—each with different space requirements.
Compatibility rules:
- Motorcycles fit in any spot size
- Cars require medium or large spots
- Buses/trucks need multiple contiguous large spots on the same floor
Core Operations:
Your system must handle:
- Vehicle arrival: Locate and assign suitable spot(s) for an incoming vehicle, or indicate no space is available
- Vehicle departure: Release occupied spot(s) and compute the parking charge based on duration
- Status queries: Report available spot counts by size and floor, plus whether the facility has reached capacity
Design Scope:
Focus on the in-memory object model, not distributed system concerns. Assume timing and payment are provided by external utilities.
What to provide:
- Core classes with their responsibilities and key fields
- How classes relate (inheritance vs. composition)
- Essential methods for the three operations above
- Which design patterns or principles guide your choices
- A complete implementation demonstrating your design
Hints
Hint 1
Consider using composition for the physical hierarchy (facility → floors → spots) and light inheritance for vehicle types
Hint 2
The compatibility check can be simplified if spot sizes form an ordered enumeration
Hint 3
Separate allocation logic from billing logic—one changes with physical constraints, the other with pricing policy
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Multi-Level Parking Facility Design
Conceptual Approach
Break the problem into three orthogonal concerns:
- Physical hierarchy: The facility contains floors, floors contain spots—pure composition
- Parked entities: Different vehicle types with different needs—minimal inheritance
- Variable policies: Spot selection and fee calculation—injectable strategies
This separation lets each piece evolve independently. Adding a new vehicle type doesn't touch allocation logic. Changing pricing doesn't affect spot management.
Core Classes
SpotSize (enum)
- Purpose: Represent comparable sizes
- Values:
SMALL = 1,MEDIUM = 2,LARGE = 3 - Using an integer enum makes compatibility a simple
>=check
Vehicle (abstract base)
- Purpose: Common interface for all parkable things
- Attributes:
license_plate,minimum_size,spot_count - Subclasses:
Motorcycle(small, 1 spot),Car(medium, 1 spot),Bus(large, 5 spots) - Design choice: Inheritance is shallow—only data differs, no behavior overrides
ParkingSpot
- Purpose: Represents one physical space
- Attributes:
floor_number,position,size,occupant(nullable Vehicle) - Methods:
is_available(),accepts(vehicle)→ bool - The
acceptsmethod encapsulates the compatibility rule: free andsize >= vehicle.minimum_size
Floor
- Purpose: Manages a collection of spots and their arrangement
- Attributes:
floor_id,spots(ordered list),availability_map(size → count) - Methods:
allocate_for(vehicle)→ list of spots or None,release(spots) - Allocation strategy:
- Single-spot vehicles: smallest compatible spot (preserves large spots for buses)
- Multi-spot vehicles: scan for a contiguous run of fitting spots
- Maintains availability counts incrementally, making queries O(1)
ParkingRecord
- Purpose: Links a vehicle to its assigned spots and entry timestamp
- Attributes:
record_id,vehicle,floor,occupied_spots,entry_time - This object carries all state needed for exit processing
FeeCalculator (interface)
- Purpose: Pluggable billing logic
- Method:
compute_fee(record, exit_time)→ amount - Example implementations: hourly rate, flat fee, tiered by vehicle type
- Injected into the facility, supporting different pricing models without changing core logic
ParkingFacility (facade)
- Purpose: Unified entry point coordinating all operations
- Attributes:
floors,active_records(plate → record),fee_calculator,time_source - Methods:
enter_vehicle(vehicle)→ record or Noneexit_vehicle(plate)→ feeavailable_spots_by_size(),available_spots_by_floor(),is_at_capacity()
Relationships
- Composition: Facility owns floors, floors own spots. Spots don't exist independently.
- Inheritance: Vehicle subclasses extend the abstract base, following Liskov Substitution (any subclass works wherever Vehicle is expected).
- Association: ParkingRecord associates a vehicle with specific spots on a specific floor.
- Dependency Inversion: Facility depends on FeeCalculator abstraction, not concrete billing logic.
Key Methods
ParkingFacility.enter_vehicle(vehicle):
- Check if
vehicle.license_platealready has an active record (reject duplicates) - Iterate through floors calling
floor.allocate_for(vehicle) - On first success, mark spots occupied, create record, return it
- If all floors return None, return None (facility can't accommodate)
Floor.allocate_for(vehicle):
- If
vehicle.spot_count == 1: find smallest compatible available spot using min-heap or linear scan - If
vehicle.spot_count > 1: sliding window through spots to find contiguous run where allaccept(vehicle) - Return list of allocated spots, or None if no fit found
ParkingFacility.exit_vehicle(plate):
- Look up and remove record from
active_records - Call
record.floor.release(record.occupied_spots)to mark spots available - Compute
fee = fee_calculator.compute_fee(record, current_time) - Return fee (payment processing happens externally)
Query methods:
available_spots_by_size(): aggregatefloor.availability_mapacross all floorsavailable_spots_by_floor(): sum free spots per flooris_at_capacity(): return total free spots == 0
Design Principles Applied
Single Responsibility:
- Spots manage occupancy state
- Floors handle spatial layout and adjacency
- Facility coordinates across floors
- Fee calculation lives separately
Open/Closed:
Adding a new vehicle type (e.g., Van requiring 2 large spots) means creating a subclass with appropriate attributes. No changes to allocation code since it works with the abstract Vehicle interface.
Strategy Pattern: FeeCalculator can be swapped at runtime (hourly, daily, surge pricing) without modifying ParkingFacility. Similarly, allocation strategy could be extracted if different facilities want different selection rules (nearest to exit, random, etc.).
Dependency Inversion: Facility depends on abstractions (FeeCalculator interface, time_source function) rather than concrete implementations. This makes testing straightforward—inject a fixed clock and predictable fee calculator.
Liskov Substitution:
Any Vehicle subclass honors the contract: it declares what it needs via minimum_size and spot_count. The allocation algorithm never type-checks; it only reads these attributes.
Complexity Analysis
Let F = number of floors, S = spots per floor.
- Enter: O(F·S) worst case for scanning floors and spots. Optimizations:
- Maintain per-floor heaps keyed by spot size for O(F·log S) single-spot allocation
- For multi-spot vehicles, track free runs explicitly
- Exit: O(k) where k = number of spots released, plus O(1) record lookup
- Queries: O(F) to aggregate across floors; can optimize to O(1) with global counters
- Space: O(total spots + active vehicles)
Edge Cases and Trade-offs
Fragmentation: "Not at capacity" doesn't guarantee a bus fits. A facility with only scattered single large spots can't accommodate a bus needing 5 contiguous. Query methods should clarify this distinction.
Duplicate entry: Attempting to park an already-parked plate is rejected immediately. The active_records map prevents double-booking.
Unknown exit: Exiting a plate not in active_records raises an error rather than charging nothing.
Multi-floor buses: Not supported—contiguous spots must be on a single floor. Relaxing this would require modeling inter-floor adjacency, significantly complicating allocation.
Concurrency: If multiple threads call enter/exit simultaneously, wrap these methods in locks. The find-then-occupy sequence must be atomic to avoid double-booking.
Fee rounding: Bill for partial hours by ceiling (e.g., 1.2 hours → 2 hours), with a minimum charge period.
Implementation
from abc import ABC, abstractmethod
from dataclasses import dataclass
from datetime import datetime
from enum import IntEnum
from typing import Callable, Optional
class SpotSize(IntEnum):
SMALL = 1
MEDIUM = 2
LARGE = 3
class Vehicle(ABC):
def __init__(self, plate: str):
self.license_plate = plate
@property
@abstractmethod
def minimum_size(self) -> SpotSize:
pass
@property
def spot_count(self) -> int:
return 1
class Motorcycle(Vehicle):
@property
def minimum_size(self) -> SpotSize:
return SpotSize.SMALL
class Car(Vehicle):
@property
def minimum_size(self) -> SpotSize:
return SpotSize.MEDIUM
class Bus(Vehicle):
@property
def minimum_size(self) -> SpotSize:
return SpotSize.LARGE
@property
def spot_count(self) -> int:
return 5
class ParkingSpot:
def __init__(self, floor_num: int, position: int, size: SpotSize):
self.floor_number = floor_num
self.position = position
self.size = size
self.occupant: Optional[Vehicle] = None
def is_available(self) -> bool:
return self.occupant is None
def accepts(self, vehicle: Vehicle) -> bool:
return self.is_available() and self.size >= vehicle.minimum_size
@dataclass
class ParkingRecord:
record_id: int
vehicle: Vehicle
floor: 'Floor'
occupied_spots: list[ParkingSpot]
entry_time: datetime
class Floor:
def __init__(self, floor_id: int, spot_sizes: list[SpotSize]):
self.floor_id = floor_id
self.spots = [
ParkingSpot(floor_id, i, size)
for i, size in enumerate(spot_sizes)
]
self.availability_map = {s: 0 for s in SpotSize}
for size in spot_sizes:
self.availability_map[size] += 1
def allocate_for(self, vehicle: Vehicle) -> Optional[list[ParkingSpot]]:
if vehicle.spot_count == 1:
candidates = [s for s in self.spots if s.accepts(vehicle)]
if not candidates:
return None
chosen = min(candidates, key=lambda s: s.size)
chosen.occupant = vehicle
self.availability_map[chosen.size] -= 1
return [chosen]
else:
# Find contiguous run
for start in range(len(self.spots) - vehicle.spot_count + 1):
run = self.spots[start:start + vehicle.spot_count]
if all(spot.accepts(vehicle) for spot in run):
for spot in run:
spot.occupant = vehicle
self.availability_map[spot.size] -= 1
return run
return None
def release(self, spots: list[ParkingSpot]) -> None:
for spot in spots:
self.availability_map[spot.size] += 1
spot.occupant = None
def total_free_spots(self) -> int:
return sum(self.availability_map.values())
class FeeCalculator(ABC):
@abstractmethod
def compute_fee(self, record: ParkingRecord, exit_time: datetime) -> float:
pass
class HourlyFeeCalculator(FeeCalculator):
def __init__(self, rate_per_hour: float):
self.rate = rate_per_hour
def compute_fee(self, record: ParkingRecord, exit_time: datetime) -> float:
duration = (exit_time - record.entry_time).total_seconds() / 3600
hours = max(1, int(duration) + (1 if duration % 1 > 0 else 0))
return hours * self.rate
class ParkingFacility:
def __init__(
self,
floors: list[Floor],
fee_calculator: FeeCalculator,
time_source: Callable[[], datetime] = datetime.now
):
self.floors = floors
self.fee_calculator = fee_calculator
self.time_source = time_source
self.active_records: dict[str, ParkingRecord] = {}
self._next_record_id = 1
def enter_vehicle(self, vehicle: Vehicle) -> Optional[ParkingRecord]:
if vehicle.license_plate in self.active_records:
raise ValueError(f"Vehicle {vehicle.license_plate} already parked")
for floor in self.floors:
spots = floor.allocate_for(vehicle)
if spots:
record = ParkingRecord(
self._next_record_id,
vehicle,
floor,
spots,
self.time_source()
)
self._next_record_id += 1
self.active_records[vehicle.license_plate] = record
return record
return None
def exit_vehicle(self, plate: str) -> float:
if plate not in self.active_records:
raise ValueError(f"Vehicle {plate} not found")
record = self.active_records.pop(plate)
record.floor.release(record.occupied_spots)
return self.fee_calculator.compute_fee(record, self.time_source())
def available_spots_by_size(self) -> dict[SpotSize, int]:
totals = {s: 0 for s in SpotSize}
for floor in self.floors:
for size, count in floor.availability_map.items():
totals[size] += count
return totals
def available_spots_by_floor(self) -> dict[int, int]:
return {f.floor_id: f.total_free_spots() for f in self.floors}
def is_at_capacity(self) -> bool:
return all(f.total_free_spots() == 0 for f in self.floors)
This design balances extensibility with simplicity. The core model is straightforward enough to implement in an interview while demonstrating solid OO principles and awareness of real-world concerns like fee policies and edge cases.