Skip to main content
02

Design a parking lot system

EasyOOPSOLIDStrategy patternConcurrency

Design the classes for a parking lot system: a multi-level garage with different spot sizes, where vehicles get a ticket on entry, park in a suitable spot, and pay on exit.

A typical framing: "The lot has several floors with motorcycle, compact and large spots. Entry gates issue tickets, exit gates take payment. Show me the main classes, how a spot is assigned, how the fee is calculated, and how you'd extend it later."

TL;DR

This is an object-oriented design question: the interviewer wants clean responsibilities, sensible abstractions and code that's easy to extend. Identify the nouns (ParkingLot, Floor, Spot, Vehicle, Ticket, Gate) and give each one job. Keep the rules that change behind interfaces: a SpotAssignmentStrategy decides where a vehicle parks, a PricingStrategy decides what it pays. This is the Strategy pattern and the open/closed principle in practice.

Model vehicle and spot types as enums with a "fits in" rule, not a deep class hierarchy. Spot assignment must be atomic because several gates work in parallel, so guard it with a lock (in memory) or a conditional update (in a database). Ticket and payment follow a small state machine.

1. Requirements

Questions worth asking:

  • Which vehicle and spot types? Can a motorcycle use a compact spot?
  • How many entry and exit gates? (Several gates means concurrency.)
  • How is the fee calculated: hourly, daily cap, different per vehicle type?
  • Do we need to show free spots per floor on a display board?
  • Payment methods? Lost tickets?

Functional

  • Issue a ticket on entry and assign a suitable spot, or reject when full.
  • Calculate the fee and accept payment on exit, then free the spot.
  • Show the number of free spots per type per floor.

Non-functional

  • No two vehicles get the same spot, even when gates work in parallel.
  • Easy to add a new vehicle type, pricing rule or assignment rule.

2. Entities and classes

Loading diagram...
ts
enum VehicleType {
  Motorcycle,
  Car,
  Truck,
}
enum SpotType {
  Motorcycle,
  Compact,
  Large,
}

/** Which spot types each vehicle may use, in order of preference. */
const allowedSpots: Record<VehicleType, SpotType[]> = {
  [VehicleType.Motorcycle]: [SpotType.Motorcycle, SpotType.Compact, SpotType.Large],
  [VehicleType.Car]: [SpotType.Compact, SpotType.Large],
  [VehicleType.Truck]: [SpotType.Large],
}

A table like allowedSpots beats subclasses such as Car extends Vehicle with overridden methods: the vehicles don't behave differently, they just have different sizes. Inheritance is for different behavior, not different data.

3. API

ts
interface ParkingService {
  /** Throws LotFullError if no suitable spot is free. */
  park(vehicle: Vehicle, gateId: string): Ticket
  quote(ticketId: string, at?: Date): Money
  /** Frees the spot only after a successful payment. */
  leave(ticketId: string, payment: Payment): Receipt
  availability(): Record<number, Record<SpotType, number>>
}

If this were exposed over HTTP: POST /tickets (entry), GET /tickets/{id}/quote, POST /tickets/{id}/payments (with an idempotency key) and GET /availability.

4. Core logic

ts
class Spot {
  private vehicle: Vehicle | null = null
  constructor(
    readonly id: string,
    readonly type: SpotType,
  ) {}
  isFree() {
    return this.vehicle === null
  }
  assign(vehicle: Vehicle) {
    if (!this.isFree()) throw new Error(`Spot ${this.id} is taken`)
    this.vehicle = vehicle
  }
  release() {
    this.vehicle = null
  }
}

interface SpotAssignmentStrategy {
  findSpot(floors: Floor[], vehicle: Vehicle): Spot | null
}

/** Lowest floor first, smallest suitable spot first. */
class NearestFirstStrategy implements SpotAssignmentStrategy {
  findSpot(floors: Floor[], vehicle: Vehicle) {
    for (const floor of floors) {
      for (const type of allowedSpots[vehicle.type]) {
        const spot = floor.firstFree(type) // O(1) with a free list per type
        if (spot) return spot
      }
    }
    return null
  }
}

class ParkingLot {
  private readonly lock = new Mutex()
  constructor(
    private floors: Floor[],
    private assignment: SpotAssignmentStrategy,
    private pricing: PricingStrategy,
    private tickets: TicketRepository,
  ) {}

  async park(vehicle: Vehicle): Promise<Ticket> {
    // Find and assign must be one atomic step, or two gates can grab the same spot.
    return this.lock.runExclusive(() => {
      const spot = this.assignment.findSpot(this.floors, vehicle)
      if (!spot) throw new LotFullError()
      spot.assign(vehicle)
      return this.tickets.create({ spot, vehicle, entryTime: new Date(), status: 'active' })
    })
  }

  async leave(ticketId: string, payment: Payment): Promise<Receipt> {
    const ticket = this.tickets.get(ticketId)
    if (ticket.status !== 'active') throw new InvalidTicketError()
    const amount = this.pricing.price(ticket, new Date())
    const receipt = await payment.charge(amount)
    ticket.status = 'paid'
    ticket.spot.release()
    return receipt
  }
}

A pricing strategy:

ts
class HourlyPricing implements PricingStrategy {
  constructor(
    private ratePerHour: Record<VehicleType, number>,
    private dailyCap: number,
  ) {}
  price(ticket: Ticket, exitTime: Date) {
    const hours = Math.ceil((exitTime.getTime() - ticket.entryTime.getTime()) / 3_600_000)
    const days = Math.floor(hours / 24)
    const rest = Math.min((hours % 24) * this.ratePerHour[ticket.vehicle.type], this.dailyCap)
    return days * this.dailyCap + rest
  }
}

Each floor keeps a free list (or set) per spot type, so finding a spot is O(floors × types) instead of scanning every spot, and the availability board is just the list sizes.

5. Edge cases and extensions

  • Concurrency with a database: instead of an in-process lock, claim the spot with a conditional update: UPDATE spots SET vehicle_id = ? WHERE id = ? AND vehicle_id IS NULL. If no row changed, another gate won; try the next spot.
  • Ticket state machine: active → paid → exited, plus lost. A lost ticket is priced with a flat fee or from the entry camera's plate record.
  • Payment failure: the spot stays occupied and the ticket stays active; never free the spot before the money is confirmed.
  • New rules: electric charging spots, reservations or valet are new spot types or new strategies, with no changes to ParkingLot.
  • Observer pattern: the display boards subscribe to spot changes instead of polling.

Common follow-ups

  • "Why not a Car subclass?" Because cars, trucks and motorcycles differ only in data (size), not behavior. Composition and enums keep it simple; add classes when behavior differs.
  • "How would you make it a service for 1,000 lots?" Store spots and tickets in a database partitioned by lot id, keep the same strategies, and use conditional updates for assignment.
  • "How do you test it?" Inject a fake clock into pricing, and test the assignment strategy with hand-built floors, including the "lot full" and "only a larger spot left" cases.

What interviewers look for

  • Clear entities with single responsibilities.
  • Strategy pattern for the rules that change (assignment, pricing): open for extension, closed for modification.
  • Composition and enums over needless inheritance.
  • Awareness of concurrency at the gates.
  • A state machine for tickets and correct ordering of payment and release.

Was this helpful?

Related questions