Skip to content

Lesson 13 of 32Technical rounds

Object-Oriented (Low-Level) Design Round

Turn a prompt like 'design a parking lot' into clear classes, working core code and good answers to the extension and concurrency follow-ups.

21 min read0/5 questions

"Design a parking lot." You have 45 minutes, a shared editor, and an interviewer who will not tell you what a parking lot needs. This is the object-oriented design round, also called low-level design (LLD) or machine coding. It is common at Amazon, Microsoft, Uber and many companies outside big tech, and it often replaces system design for junior and mid-level candidates. It tests the skill you use most at work: turning fuzzy requirements into classes and interfaces that someone else can read, test and extend. This lesson gives you a process, then works the parking lot end to end in runnable Python, including the follow-ups that decide the grade.

What the round is, and is not

You design the classes, their responsibilities and their interfaces for a bounded system, then code the core paths. Typical prompts: parking lot, elevator system, vending machine, library management, deck of cards, an in-memory file system, a rate limiter class, a snake game, a splitwise-style expense sharer.

It is not system design. There are no load balancers, databases or replicas unless the interviewer brings them up. If you start drawing servers, you have misread the round. Think "the code inside one service" rather than "the services".

It is also not a pattern quiz. Interviewers are not counting how many patterns you name. They score roughly this:

  • Requirements: did you pin down scope before designing?
  • Modelling: are the entities sensible, with clear responsibilities and no god class?
  • Interfaces: are method names and signatures clear, and do they hide internals?
  • Working code: do the core use cases actually run?
  • Extensibility: when the interviewer adds a requirement, how much code has to change?
  • Communication: do you explain trade-offs as you go?

The process

MinutesStepOutput
0–5Clarify use casesA short list of in-scope actions, and what is out
5–10Entities and responsibilitiesNouns become candidate classes, each with one job
10–15Relationships and interfacesWho owns whom, the public methods and their signatures
15–35Code the core pathsEnums, data classes, the main service class, a demo
35–45Extensions and concurrencyHow new requirements fit; what breaks with two callers

Clarify use cases. For a parking lot, ask: Which vehicle types? Which spot sizes, and can a small vehicle use a big spot? One level or several? How is pricing calculated: hourly, flat, by vehicle? Is payment in scope, or just the fee? Do we need a display of free spots? Then say what you will leave out: "I'll skip payment processing and reservations, and treat the clock as an input so it is easy to test."

Entities and responsibilities. Underline the nouns: vehicle, spot, ticket, lot, pricing. For each, say its one job. A Spot knows whether a vehicle fits. A Ticket records who parked where and when. A PricingStrategy turns a duration into a fee. The ParkingLot coordinates. If one class ends up doing everything, that is the god class interviewers look for.

Relationships. Default to composition: the lot has spots and has a pricing strategy. Use inheritance only for a real "is a" relationship where subclasses are interchangeable. A classic weak answer is class Car(Vehicle), class Truck(Vehicle), class Motorcycle(Vehicle) with no behaviour difference between them. If the only difference is a size, a size field on one Vehicle class is simpler and adding a new vehicle type stops needing a new class.

Quick check
Your Car, Motorcycle and Truck subclasses differ only in which spot sizes they fit. What is the better model?
Need a nudge? A hint rules out a wrong answer.
Parking lot: who owns what
ParkingLot: park(), leave()ParkingLotpark(), leave()Spot: size, vehicle, fits()Spotsize, vehicle, fits()Vehicle: plate, sizeVehicleplate, sizeTicket: id, spot, entered_atTicketid, spot, entered_atPricingStrategy: fee(size, minutes)PricingStrategyfee(size, minutes)HourlyPricing: per started hourHourlyPricingper started hourFlatRatePricing: one priceFlatRatePricingone pricehas manyholds 0 or 1issuesusesimplementsimplements

ParkingLot is the only class callers talk to. It coordinates; it does not know how fees are calculated.

1/4

The worked example: a parking lot in Python

Agreed scope: three sizes (motorcycle, compact, large); a vehicle fits any spot at least its size; pick the smallest spot that fits; hourly pricing per started hour with a one-hour minimum, varying by vehicle size; leave by ticket id and get the fee; refuse cleanly when full. Time is passed in as minutes so the demo is deterministic.

Pythonparking_lot.py
from __future__ import annotations import itertoolsimport mathimport threadingfrom abc import ABC, abstractmethodfrom dataclasses import dataclassfrom enum import IntEnum class Size(IntEnum): """Ordered, so a bigger spot can take a smaller vehicle.""" MOTORCYCLE = 1 COMPACT = 2 LARGE = 3 @dataclass(frozen=True)class Vehicle: plate: str size: Size @dataclassclass Spot: spot_id: str size: Size vehicle: Vehicle | None = None def fits(self, vehicle: Vehicle) -> bool: return self.vehicle is None and vehicle.size <= self.size @dataclass(frozen=True)class Ticket: ticket_id: int plate: str spot_id: str entered_at: int # minutes since opening; a real system would use datetime class PricingStrategy(ABC): @abstractmethod def fee(self, size: Size, minutes: int) -> int: """Return the fee in cents.""" class HourlyPricing(PricingStrategy): RATES = {Size.MOTORCYCLE: 100, Size.COMPACT: 200, Size.LARGE: 400} def fee(self, size: Size, minutes: int) -> int: hours = max(1, math.ceil(minutes / 60)) # any part hour counts, minimum 1 return hours * self.RATES[size] class FlatRatePricing(PricingStrategy): def __init__(self, cents: int) -> None: self.cents = cents def fee(self, size: Size, minutes: int) -> int: return self.cents class LotFullError(Exception): pass class ParkingLot: def __init__(self, spots: list[Spot], pricing: PricingStrategy) -> None: self._spots = sorted(spots, key=lambda s: s.size) # smallest first self._pricing = pricing self._active: dict[int, Ticket] = {} self._ids = itertools.count(1) self._lock = threading.Lock() def park(self, vehicle: Vehicle, now: int) -> Ticket: with self._lock: # find and claim must be one atomic step spot = next((s for s in self._spots if s.fits(vehicle)), None) if spot is None: raise LotFullError(f"no spot for {vehicle.plate}") spot.vehicle = vehicle ticket = Ticket(next(self._ids), vehicle.plate, spot.spot_id, now) self._active[ticket.ticket_id] = ticket return ticket def leave(self, ticket_id: int, now: int) -> int: with self._lock: ticket = self._active.pop(ticket_id) # KeyError if unknown or used twice spot = next(s for s in self._spots if s.spot_id == ticket.spot_id) size = spot.vehicle.size spot.vehicle = None return self._pricing.fee(size, now - ticket.entered_at) def free_count(self) -> int: return sum(s.vehicle is None for s in self._spots) lot = ParkingLot( [Spot("M1", Size.MOTORCYCLE), Spot("C1", Size.COMPACT), Spot("C2", Size.COMPACT), Spot("L1", Size.LARGE)], HourlyPricing(),) bike = lot.park(Vehicle("BK-01", Size.MOTORCYCLE), now=0)car = lot.park(Vehicle("CR-22", Size.COMPACT), now=5)van = lot.park(Vehicle("VN-77", Size.LARGE), now=10)print(bike.spot_id, car.spot_id, van.spot_id, "free:", lot.free_count()) print("car pays", lot.leave(car.ticket_id, now=5 + 61), "cents") # 61 min -> 2 hours try: lot.park(Vehicle("TR-99", Size.LARGE), now=70)except LotFullError as e: print("refused:", e) weekend = ParkingLot([Spot("C1", Size.COMPACT)], FlatRatePricing(500))t = weekend.park(Vehicle("CR-22", Size.COMPACT), now=0)print("weekend pays", weekend.leave(t.ticket_id, now=600), "cents")
Output
Press Run (⌘ Enter) to see what happens.

What to say about the choices as you write them:

  • IntEnum for size makes "fits" a plain comparison, vehicle.size <= self.size. A plain Enum would need a lookup table. Saying why you chose the type is a quiet signal of experience.
  • Frozen dataclasses for Vehicle and Ticket: they are values that should never change after creation, and freezing them makes them hashable and safe to share.
  • Money in integer cents, never floats. 0.1 + 0.2 is not 0.3 in binary floating point, and fee bugs are the kind that reach customers.
  • The clock is an argument. now is passed in instead of calling the system clock inside the class, so tests are deterministic. This is dependency injection at its simplest.
  • Private attributes (_spots, _active) keep callers on the public methods. The lot's internals can change without breaking anyone.
  • A specific exception for a full lot rather than returning None, so callers cannot accidentally ignore it.

The spot choice is a deliberate policy: smallest fitting spot first. It keeps large spots free for large vehicles, but it is not perfect, and interviewers like to poke at it.

Predict the outputPython

What does this print?

spots = [("L1", 3), ("M1", 1), ("C1", 2)]
spots.sort(key=lambda s: s[1])
taken = set()

def park(size):
  for sid, cap in spots:
      if sid not in taken and size <= cap:
          taken.add(sid)
          return sid
  return None

print(park(1), park(1), park(3), park(2))
Need a nudge? Hints walk you through it.

Patterns where they earn their keep

Interviewers like patterns that solve a stated problem and dislike patterns added for decoration. The Behavioral Patterns and Creational Patterns lessons cover these in depth; here is when each one naturally appears in an LLD round.

  • Strategy when a rule has several versions that change independently: pricing, spot assignment (smallest fit, nearest the exit), elevator scheduling. The parking lot above takes any PricingStrategy, so adding a tariff never touches ParkingLot. That is the open/closed principle from SOLID Principles in practice.
  • State when an object behaves differently depending on its mode and only some transitions are legal: vending machine (idle, has money, dispensing), elevator (idle, moving up, moving down, doors open), order lifecycle.
  • Observer when other parts must react to an event without the source knowing who they are: a display board updating free-spot counts, notifications when a book you reserved is returned.
  • Factory when creation logic is non-trivial or chosen at run time: building the right PricingStrategy from a config string, creating levels with a given layout.
  • Singleton: be careful. "There is only one parking lot" is a common reason given, but a module-level instance or simply creating one and passing it in does the same job and stays testable. Saying that is a better answer than reaching for the pattern.

Apply SOLID as a check, not a ceremony. Single responsibility: can you describe each class without "and"? Dependency inversion: does ParkingLot depend on the PricingStrategy interface rather than a concrete class? Do not add interfaces for things with exactly one implementation and no plan for a second.

Match the pairs0/4 matched

Match each requirement to the pattern that fits it best.

Choose an item, then its match on the other side.

The vending machine: State with a discriminated union

State shows up in the vending machine and elevator prompts. In TypeScript, a discriminated union is the cleanest way to write it: each state is a type with its own data, and the compiler checks that you handle every case. A machine with money has a credit; an idle machine cannot, so there is no invalid "idle with 150 cents" state to worry about.

Vending machine states
idlehasMoneydispensinginsertrefundselect (enough credit)taken

currentwaitingdone

Pressing a button in idle has no edge, so nothing happens. No money, no item.

1/4
TypeScriptvending_machine.ts
type State = | { kind: "idle" } | { kind: "hasMoney"; credit: number } | { kind: "dispensing"; item: string; change: number }; type Event = | { type: "insert"; cents: number } | { type: "select"; item: string; price: number } | { type: "refund" } | { type: "taken" }; function next(state: State, event: Event): State { switch (state.kind) { case "idle": if (event.type === "insert") return { kind: "hasMoney", credit: event.cents }; return state; // selecting with no money does nothing case "hasMoney": if (event.type === "insert") return { kind: "hasMoney", credit: state.credit + event.cents }; if (event.type === "refund") return { kind: "idle" }; if (event.type === "select" && state.credit >= event.price) { return { kind: "dispensing", item: event.item, change: state.credit - event.price }; } return state; // not enough credit: stay put case "dispensing": if (event.type === "taken") return { kind: "idle" }; return state; // ignore coins and buttons mid-dispense }} let s: State = { kind: "idle" };const events: Event[] = [ { type: "select", item: "water", price: 150 }, { type: "insert", cents: 100 }, { type: "select", item: "water", price: 150 }, { type: "insert", cents: 100 }, { type: "select", item: "water", price: 150 }, { type: "insert", cents: 50 }, { type: "taken" },];for (const e of events) { s = next(s, e); console.log(e.type.padEnd(7), "->", JSON.stringify(s));}
Output
Press Run (⌘ Enter) to see what happens.

The Python equivalents: an Enum for the state names plus a transition table, or one small class per state behind an abc.ABC when each state has real behaviour. In either language, mention that a pure next(state, event) function is trivially testable, which is a design argument in itself.

The concurrency follow-up

Almost every LLD round ends with some version of: "Two cars arrive at two gates at the same moment. Can they get the same spot?" With a naive design, yes. Finding a free spot and claiming it are two separate steps, and the other gate can run between them. This is a check-then-act race.

Pythontwo_gates.py
# Two gate machines handle cars at the same moment.# We play out the interleaving by hand so it is the same every run.spots = {"C1": None, "C2": None} def find_free(): return next(sid for sid, car in spots.items() if car is None) # Check-then-act, split across two stepsa_choice = find_free() # gate A looks: C1 is freeb_choice = find_free() # gate B looks before A writes: C1 is freespots[a_choice] = "CAR-A" # gate A claims C1spots[b_choice] = "CAR-B" # gate B claims C1 too, overwriting Aprint("unsafe:", spots) # Fix: claim with compare-and-set, and retry if someone beat you to itspots = {"C1": None, "C2": None} def try_claim(sid, car): # In a real system this whole function runs under a lock, or as one # conditional database UPDATE, so nothing can run between check and set. if spots[sid] is None: spots[sid] = car return True return False def park(car): while True: sid = find_free() if try_claim(sid, car): return sid a_choice = find_free() # A looks: C1b_choice = find_free() # B looks: C1print("A claims C1:", try_claim(a_choice, "CAR-A"))print("B claims C1:", try_claim(b_choice, "CAR-B"))print("B retries and gets:", park("CAR-B"))print("safe:", spots)
Output
Press Run (⌘ Enter) to see what happens.

Car A has silently vanished from the unsafe version: it holds a ticket for a spot that someone else is in. Three fixes, in order of how far they scale:

  1. A lock around find-and-claim, as ParkingLot.park does with threading.Lock. Simple and correct inside one process. The cost is that every park waits for the lock, which is fine at parking-lot speeds.
  2. Finer-grained locks, such as one per level, so gates on different levels do not block each other. More throughput, more complexity, and a deadlock risk if code ever takes two locks in different orders.
  3. Compare-and-set in the database once there are several servers: UPDATE spots SET vehicle = :plate WHERE id = :id AND vehicle IS NULL, then check that exactly one row changed. If zero changed, someone beat you to it, so pick another spot and retry. An in-process lock cannot protect you across machines; the database row can.

Name the trade-off and stop. You do not need to build a distributed system; you need to show you saw the race and know which tool fits which scale.

Quick check
The parking lot now runs on three servers behind a load balancer, sharing one database. Why is the threading.Lock in ParkingLot no longer enough?
Need a nudge? A hint rules out a wrong answer.

Extension questions, and how to answer them

After the core works, expect two or three "what if" questions. Answer each by saying which class changes and which does not. That is the evidence your design is extensible.

  • "Add electric-vehicle charging spots." Add a charging: bool capability on Spot and a needs_charging on Vehicle; extend fits(). Pricing could add a charging fee through a new strategy or a decorator around the existing one. ParkingLot.park does not change.
  • "Multiple levels, and a display per level." Introduce Level, which owns its spots; the lot owns levels. The display subscribes to spot-freed and spot-taken events (Observer).
  • "Monthly pass holders park free." A new pricing strategy that checks a pass registry, or a check before pricing. Ask whether passes reserve a spot; that changes the model.
  • "Lost ticket." Look up the active ticket by plate (add an index from plate to ticket id) and charge a fixed lost-ticket fee as policy.
Put it in order5 steps

Put the steps of an object-oriented design round in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Common mistakes

  • Coding before scoping. Ten minutes into a class hierarchy for payment methods that were never in scope.
  • A god class. ParkingLot that calculates fees, prints receipts, sends emails and validates plates.
  • Inheritance for data. Subclasses that differ only in a field.
  • Getters and setters for everything. Expose behaviour (park, leave), not raw fields to be changed from outside.
  • Patterns without problems. A singleton, an abstract factory and a visitor in a design that needs none of them.
  • Never running anything. A diagram and stubs with pass score below a smaller design that actually works.
  • Floats for money, and wall-clock time inside the class. Both make bugs and make tests flaky.
Key terms
low-level design (LLD)
An interview round where you design classes, responsibilities and interfaces for a bounded system and code the core paths.
composition
Building an object from other objects it owns or uses, a has-a relationship, preferred over inheritance in most designs.
god class
One class that has taken on most of the system's responsibilities, making it hard to read, test and change.
discriminated union
A TypeScript union of object types sharing a literal tag field, so the compiler can narrow and check every case.
check-then-act race
A bug where a condition is checked and then acted on in separate steps, letting another caller change things in between.
compare-and-set
An atomic operation that writes a new value only if the current value is still the expected one, reporting whether it succeeded.
IntEnum
A Python enum whose members are also integers, so they can be ordered and compared directly.