Low-Level Design Interviews
A repeatable approach to object-oriented design interviews — clarifying requirements, finding entities, assigning responsibilities, applying patterns — with a fully worked parking lot design and a list of common problems.
Low-level design (LLD) interviews — also called object-oriented design or machine-coding rounds — ask you to model a system as classes and implement its core logic in 45–90 minutes: a parking lot, an elevator, a library, a rate limiter, a chess game. Interviewers look for clear abstractions, sensible responsibilities, extensibility, and working code, not pattern name-dropping.
A repeatable approach
- Clarify requirements (5 min). Ask about scope: which features, which actors, scale, concurrency. Write down a short list of use cases and explicitly park the rest.
- Identify entities. Underline the nouns: they're candidate classes. Verbs become methods.
- Define relationships. Has-a vs is-a, multiplicities. Sketch a quick class diagram (UML).
- Assign responsibilities. Each class owns its data and the behaviour that uses it. Ask "who knows the information needed to do this?"
- Find what varies and put it behind interfaces: pricing, allocation strategy, notification channels. This is where patterns earn their place.
- Write the core code: models, the main service, the key algorithm. Use enums, immutable value objects, and clear names.
- Handle edge cases and concurrency: full lot, double booking, invalid states.
- Discuss extensions: how a new vehicle type, pricing rule or floor would be added.
Worked example: parking lot
Requirements (after clarifying): multiple floors with spots of sizes small/medium/large; vehicles are motorcycles, cars and trucks; a vehicle parks in the smallest free spot that fits; issue a ticket on entry; on exit compute the fee by duration and vehicle type; show free spots per floor. Multiple entry gates operate concurrently.
Entities: ParkingLot, Floor, Spot, Vehicle (+ type), Ticket, FeeCalculator / PricingStrategy, SpotAllocationStrategy.
enum SpotSize { SMALL, MEDIUM, LARGE }
enum VehicleType {
MOTORCYCLE(SpotSize.SMALL), CAR(SpotSize.MEDIUM), TRUCK(SpotSize.LARGE);
final SpotSize minSize;
VehicleType(SpotSize minSize) { this.minSize = minSize; }
}
record Vehicle(String plate, VehicleType type) {}
final class Spot {
final String id; final SpotSize size;
private Vehicle occupant;
Spot(String id, SpotSize size) { this.id = id; this.size = size; }
boolean isFree() { return occupant == null; }
boolean fits(Vehicle v) { return size.compareTo(v.type().minSize) >= 0; }
void occupy(Vehicle v) { occupant = v; }
void release() { occupant = null; }
}
record Ticket(String id, Vehicle vehicle, Spot spot, Instant entry) {}
interface SpotAllocator { Optional<Spot> find(List<Floor> floors, Vehicle v); }
interface PricingStrategy { long feeCents(Ticket t, Instant exit); }
final class Floor {
final int number;
final List<Spot> spots;
Floor(int number, List<Spot> spots) { this.number = number; this.spots = spots; }
long freeCount(SpotSize s) { return spots.stream().filter(x -> x.size == s && x.isFree()).count(); }
}
/** Smallest fitting spot, lowest floor first. */
final class SmallestFitAllocator implements SpotAllocator {
public Optional<Spot> find(List<Floor> floors, Vehicle v) {
for (SpotSize size : SpotSize.values()) {
if (size.compareTo(v.type().minSize) < 0) continue;
for (Floor f : floors)
for (Spot s : f.spots)
if (s.size == size && s.isFree()) return Optional.of(s);
}
return Optional.empty();
}
}
final class HourlyPricing implements PricingStrategy {
private final Map<VehicleType, Long> centsPerHour;
HourlyPricing(Map<VehicleType, Long> rates) { this.centsPerHour = rates; }
public long feeCents(Ticket t, Instant exit) {
long minutes = Duration.between(t.entry(), exit).toMinutes();
long hours = Math.max(1, (minutes + 59) / 60); // round up, min 1 hour
return hours * centsPerHour.get(t.vehicle().type());
}
}
public final class ParkingLot {
private final List<Floor> floors;
private final SpotAllocator allocator;
private final PricingStrategy pricing;
private final Clock clock;
private final Map<String, Ticket> active = new ConcurrentHashMap<>();
public ParkingLot(List<Floor> floors, SpotAllocator a, PricingStrategy p, Clock clock) {
this.floors = floors; this.allocator = a; this.pricing = p; this.clock = clock;
}
/** Synchronised so two gates can't grab the same spot. */
public synchronized Ticket park(Vehicle v) {
Spot spot = allocator.find(floors, v)
.orElseThrow(() -> new IllegalStateException("Lot full for " + v.type()));
spot.occupy(v);
Ticket t = new Ticket(UUID.randomUUID().toString(), v, spot, clock.instant());
active.put(t.id(), t);
return t;
}
public synchronized long leave(String ticketId) {
Ticket t = active.remove(ticketId);
if (t == null) throw new IllegalArgumentException("Unknown or used ticket");
t.spot().release();
return pricing.feeCents(t, clock.instant());
}
}from dataclasses import dataclass, field
from datetime import datetime, timedelta
from enum import IntEnum, Enum
import math, threading, uuid
class SpotSize(IntEnum):
SMALL = 1
MEDIUM = 2
LARGE = 3
class VehicleType(Enum):
MOTORCYCLE = SpotSize.SMALL
CAR = SpotSize.MEDIUM
TRUCK = SpotSize.LARGE
@dataclass(frozen=True)
class Vehicle:
plate: str
type: VehicleType
@dataclass
class Spot:
id: str
size: SpotSize
occupant: Vehicle | None = None
def is_free(self): return self.occupant is None
@dataclass
class Floor:
number: int
spots: list[Spot]
@dataclass(frozen=True)
class Ticket:
id: str
vehicle: Vehicle
spot: Spot
entry: datetime
class SmallestFitAllocator:
def find(self, floors, vehicle):
for size in SpotSize:
if size < vehicle.type.value:
continue
for floor in floors:
for spot in floor.spots:
if spot.size == size and spot.is_free():
return spot
return None
class HourlyPricing:
def __init__(self, cents_per_hour: dict[VehicleType, int]):
self.rates = cents_per_hour
def fee_cents(self, ticket, exit_time):
hours = max(1, math.ceil((exit_time - ticket.entry) / timedelta(hours=1)))
return hours * self.rates[ticket.vehicle.type]
class ParkingLot:
def __init__(self, floors, allocator, pricing, now=datetime.utcnow):
self.floors, self.allocator, self.pricing, self.now = floors, allocator, pricing, now
self.active: dict[str, Ticket] = {}
self._lock = threading.Lock()
def park(self, vehicle: Vehicle) -> Ticket:
with self._lock:
spot = self.allocator.find(self.floors, vehicle)
if spot is None:
raise RuntimeError(f"lot full for {vehicle.type.name}")
spot.occupant = vehicle
ticket = Ticket(str(uuid.uuid4()), vehicle, spot, self.now())
self.active[ticket.id] = ticket
return ticket
def leave(self, ticket_id: str) -> int:
with self._lock:
ticket = self.active.pop(ticket_id, None)
if ticket is None:
raise KeyError("unknown or used ticket")
ticket.spot.occupant = None
return self.pricing.fee_cents(ticket, self.now())enum SpotSize { Small = 1, Medium = 2, Large = 3 }
const minSize = { motorcycle: SpotSize.Small, car: SpotSize.Medium, truck: SpotSize.Large } as const;
type VehicleType = keyof typeof minSize;
interface Vehicle { plate: string; type: VehicleType }
class Spot {
occupant?: Vehicle;
constructor(readonly id: string, readonly size: SpotSize) {}
get free() { return !this.occupant; }
}
interface Floor { number: number; spots: Spot[] }
interface Ticket { id: string; vehicle: Vehicle; spot: Spot; entry: Date }
interface SpotAllocator { find(floors: Floor[], v: Vehicle): Spot | undefined }
interface PricingStrategy { feeCents(t: Ticket, exit: Date): number }
const smallestFit: SpotAllocator = {
find(floors, v) {
for (const size of [SpotSize.Small, SpotSize.Medium, SpotSize.Large]) {
if (size < minSize[v.type]) continue;
for (const f of floors) {
const s = f.spots.find((s) => s.size === size && s.free);
if (s) return s;
}
}
},
};
const hourly = (rates: Record<VehicleType, number>): PricingStrategy => ({
feeCents: (t, exit) =>
Math.max(1, Math.ceil((exit.getTime() - t.entry.getTime()) / 3_600_000)) * rates[t.vehicle.type],
});
class ParkingLot {
private active = new Map<string, Ticket>();
constructor(private floors: Floor[], private allocator: SpotAllocator,
private pricing: PricingStrategy, private now = () => new Date()) {}
park(v: Vehicle): Ticket { // single-threaded event loop: no lock needed in-process
const spot = this.allocator.find(this.floors, v);
if (!spot) throw new Error(`lot full for ${v.type}`);
spot.occupant = v;
const t = { id: crypto.randomUUID(), vehicle: v, spot, entry: this.now() };
this.active.set(t.id, t);
return t;
}
leave(ticketId: string): number {
const t = this.active.get(ticketId);
if (!t) throw new Error("unknown or used ticket");
this.active.delete(ticketId);
t.spot.occupant = undefined;
return this.pricing.feeCents(t, this.now());
}
}Design choices to say out loud:
- Strategy for allocation and pricing: new rules (nearest-to-exit, weekend rates, EV spots) are new classes, not edits.
- Enums encode the vehicle-to-spot-size rule in one place.
- Injected clock makes fee calculation testable.
- Concurrency:
parkandleaveare synchronised; at higher throughput, lock per floor or keep per-size free-spot queues (ConcurrentLinkedQueue) for O(1) allocation. In a real deployment, the spot table in the database with a conditional update is the source of truth. - Extensions: payment methods (Strategy), display boards observing spot changes (Observer), entry/exit gates as separate classes, reservations.
Common LLD problems and their key ideas
| Problem | Key abstractions and patterns |
|---|---|
| Elevator system | Elevator state machine (State), request scheduling strategy (SCAN/LOOK), controller as mediator |
| Vending machine | State pattern (idle → has money → dispensing), inventory, change-making |
| Library management | Book vs BookCopy, Member, Loan, fines (Strategy), reservations queue, notifications (Observer) |
| Tic-tac-toe / chess | Board, Piece hierarchy with move rules (polymorphism), Game state, move validation, undo (Command) |
| Snake and ladders | Board with jumps map, Dice (strategy for testing), turn loop |
| Splitwise / expense sharing | Expense with split strategies (equal, exact, percent), balance sheet, debt simplification |
| Hotel / movie ticket booking | Inventory per show/date, seat locking with timeouts, concurrency control, payment |
| LRU cache | Hash map + doubly linked list; thread safety (Distributed cache) |
| Rate limiter | Token bucket per key; strategy for algorithms (Rate limiting) |
| Logger / logging framework | Levels, appenders (Strategy), chain of loggers (Chain of Responsibility), formatters, singleton/DI |
| Pub/sub or message queue | Topics, subscribers (Observer), offsets, delivery threads |
| Ride sharing (core) | Rider, Driver, Trip state machine, matching strategy, pricing strategy (surge) |
What interviewers look for
Common mistakes: diving into code without requirements; a giant Manager class doing everything; using every pattern you know; ignoring concurrency when multiple actors share resources; running out of time before any working code exists.
- Clarify → entities → relationships → responsibilities → variation points → code → edge cases → extensions.
- Put varying rules (pricing, allocation, scheduling) behind Strategy interfaces.
- Model lifecycles with enums or the State pattern; use value objects.
- Inject clocks and randomness; consider concurrency for shared resources.
- Working, readable code for the core flow beats a perfect diagram.