Classes on the whiteboard
A low-level design round asks for the classes inside one box: which objects exist, what each one remembers, which rule each one owns, and what happens when two callers arrive at once. The interviewer is testing whether the next requirement they add is a small change in your design. The trap is to start typing classes before asking a single question, then meet the follow-up with an edit to every class you wrote.
Questions
Answer each one yourself before you open it.
01Design a parking lot: several floors, bikes, cars and trucks, a ticket on entry and a fee on exit.
Four entities:
Vehicle,Spot,TicketandLot, with size as an enum. The lot keeps the spots and holds an allocation strategy behind one call,pick, so "nearest" and "smallest that fits" are two small classes, and a full lot raises one named error,LotFull.Ask first: which sizes, may a small vehicle take a bigger spot (yes, never smaller), what is charged and when, how many gates, what happens when full. Each answer lands on one class. The driver, the gate and the fee are crossed out as entities: the gate is a parameter, the fee is a sum on exit (135 minutes is 3 started hours, at 20 an hour that is 60). A spot holds its current ticket or nothing, so "is this spot free" has one answer in one place.
Follow-up The owner opens a second entrance, and some spots now have electric chargers that electric cars must use.
The second gate costs nothing: each spot already stores its distance from each gate and
pickis told which gate. Chargers cost one flag onSpot, one onVehicleand one line inSpot.fits. Neither strategy changes, which is the proof the design was right.Learn more Design a parking lot · Swap the rule, keep the class
02Design an elevator for one building: buttons inside the car, up and down buttons on each floor.
The car is a state machine: idle, moving up, moving down or doors open, and an event (a press, reaching a stop, doors closing) moves it between them. Every button adds a floor to one set of stops the car still owes, and a separate scheduler picks the next stop, so the rule can be swapped without touching the car.
Separating the scheduler is the decision the round hinges on. With the car at floor 5 and presses for 2, 9, 4, 8, 1, 7, first come first served travels 32 floors. SCAN, which keeps its heading while any stop lies ahead and only then turns, travels 12 (4 up, 8 down). The price is fairness: floor 2, pressed first, now waits for 11 floors of travel instead of 3. Say both numbers and that trade out loud.
Follow-up Now there are four cars. A call comes from floor 6, going up.
Add a dispatcher above the cars. It asks each car how soon it could reach floor 6 going up, given its state and the stops it already owes, and sends the soonest. The cars and their scheduler do not change.
Learn more Design an elevator · Tell everyone who cares (the state pattern)
03Design seat booking for a cinema: pick a seat, pay, get a ticket.
The invariant is "a seat has at most one owner", and the danger is check-then-act: two buyers both see the seat free before either writes. Every change to a seat goes through one lock held for microseconds, and because paying takes minutes the seat gets a middle state, a hold with an expiry, between free and sold.
A lock must never be held across a payment, or one slow buyer freezes the hall. The hold needs no timer thread: store the deadline with the hold and treat a hold past its deadline as free whenever someone looks. Payment then turns a live hold into a sale, and a hold that ran out is simply free again.
Follow-up The booking service now runs as many copies on many machines, sharing one database.
A lock inside one program protects nothing across copies. Put a version number on the seat row and write with a condition that the version is still the one you read: one writer wins, the other sees zero rows updated and tells the buyer the seat is gone.
Learn more Two people, one seat · The object that keeps its rules
04Design an app that splits shared expenses in a group of friends and tells each person who owes whom.
Money is whole paise in integers, never decimals. A
Groupholds a list ofExpense, and each expense records who paid, the total and each person's share, made by a split strategy (equal, exact or percentage) behind one call. No class stores a balance: a balance is paid minus owed, worked out from the ledger.Decimals drift: 100.00 split three ways does not add back to 100.00. In paise it is 3,333 each with 1 paisa left over, and the leftover has to be given to someone on purpose. Because balances are derived, all of them always add up to zero, and settling up is just one more line in the ledger. Greedy simplification (largest debtor pays largest creditor) cut 9 payments to 4 on the lesson's trip, a good heuristic but not guaranteed to be the fewest.
Follow-up Support splitting by shares: two for each adult, one for each child.
One more strategy class behind the same call that the other splits answer. The group and the expense do not change.
Learn more Who owes whom · Swap the rule, keep the class
05A shop charges delivery as standard, express or store pickup, and the code is a long if/else on the delivery kind. Redesign it.
Each rule becomes its own class behind one shared call, and the order holds whichever rule it is given: the strategy pattern. A factory is the one place that turns the word "express" into the right object, and the rule is passed in from outside so a test can hand in a fake.
A long if/else chain on a "kind" is the sign that one job has several interchangeable rules inside it, and every new kind means editing code that already works. With strategies, a new rule is a new class (open/closed), and the shared call is the extension point. Say the limit too: leave a two-branch
ifalone, because the pattern costs more lines than it saves there.Follow-up The shop adds drone delivery.
One new class,
Drone, answering the same call, plus one line in the factory that maps the worddroneto it. The order class is not opened at all.Learn more Swap the rule, keep the class · Five letters, one shop (SOLID)
06Design a library's book: members borrow, return and reserve it, and people waiting are told when it comes back.
The book is a state machine with a class per state (on the shelf, on loan, on hold), and the book hands every action to its current state, which may refuse it or swap to the next state. Telling people is the observer pattern: the book announces "I changed" to a list of subscribers and knows nothing else about them.
A missing arrow in the state machine is a refused action, so "return a book that is on the shelf" cannot happen by construction rather than by an
ifsomeone forgot. The observer costs two things worth saying: observers react in list order, and an observer that changes the book can set off a second announcement inside the first.Follow-up Add a text message to the member at the front of the reservation queue, alongside the existing email.
One new observer subscribed to the book. The book, its states and the email observer are untouched.
Learn more Tell everyone who cares · Nouns and verbs
07Design an LRU cache with get and put, both O(1).
A hash map from key to node, plus a doubly linked list with a head and a tail sentinel. The most recently used node sits next to the head, so
getunlinks the node and pushes it to the front, andputdoes the same for an existing key. For a new key at capacity, evict the node just above the tail and delete its key from the map.The map alone finds a key in one step but cannot say which entry is oldest, and the list alone keeps the order but finds a key only by walking it. Each node stores its own key so eviction knows which map entry to delete, and the invariant is that the map and the list always describe the same entries. The list is doubly linked so a node can unlink itself in two assignments, and the sentinels remove every special case for the ends. Say that
collections.OrderedDictwithmove_to_endandpopitemdoes this in a few lines, then build it anyway.Follow-up Now make it thread-safe, and add a time limit per entry.
Put one lock around the whole body of both
getandput, becausegetis also a write: it moves a node. Name sharding by key hash as the next step if readers queue. For the time limit, store a deadline with each entry and treat agetpast the deadline as a miss and remove the entry. Recency and expiry are two separate clocks, so a hit does not extend the deadline. Inject the clock so the class can be tested without waiting.Learn more Design an LRU cache · The object that keeps its rules
08Design a vending machine: coins in, pick a product, get the item and any change, cancel for a refund.
The machine is a state machine with four states:
Idle,HasMoney,DispensingandMaintenance. Each is its own small class that answers every action for its own situation, and an action that is not allowed raises one named error,Refused. Money is whole paise, never decimals. Slots hold a price and a count, and the customer's coins wait in a tray apart from the machine's own bank, so a cancel hands back exactly what they put in.Choosing the coins to give back is the hard part. Taking the biggest coin first fails when the stock is thin: owing 600 with one 500 coin and three 200 coins, greedy takes the 500, has no 100 for the last 100 and gives up, though three 200s are exact. Use a search that backs out and tries the next coin. Work out the change before moving anything, so a refusal leaves the machine untouched and the sale is all or nothing.
Follow-up An operator comes to refill it while a customer may be using it.
Add one
Maintenancestate whose actions all refuse except closing the door, and anopen_doorline onIdleandHasMoneythat refunds the tray first. Restock is allowed only inMaintenance. The customer and the operator share the slots, tray and state, so wrap every method that changes the machine in one lock. Either the sale finishes and the door opens after, or the coins are refunded and nothing is sold.Learn more Design a vending machine · Tell everyone who cares (the state pattern)
09Design a rate limiter: each API key may make a limited number of requests, and the caller gets a yes or no.
A
RateLimiterholds a map from key to a rule, and every rule answers one call,allow(). A token bucket stores two numbers per key, the tokens and the time last seen, and on each request refillsmin(capacity, tokens + elapsed * rate), then spends one token or refuses. A sliding window log is the strict alternative. The clock is injected, so tests move a fake clock and never sleep.Ask first: limited by what, bursts or smooth, one process or many servers. The bucket needs no timer, because the refill is worked out on the next request. With rate 2 and capacity 5, an empty bucket holds 0.6 tokens at 0.3 seconds and refuses, then holds 1.0 at 0.5 seconds and allows. After 5 requests at second 0, the bucket allows 2 more at second 1 where a 2.5 second window allows none, so the bucket forgives bursts and the window is strict at the cost of storing timestamps. Two threads with one key can both read one token and both spend it, so the whole
allowneeds a lock.Follow-up Free users get 3 tokens at 1 per second, paid users 20 at 5 per second, and now there are twenty servers.
Plans are data: a table from plan to rate and capacity, looked up when a key's bucket is first created, and
TokenBucketis untouched. Twenty servers each keep their own map, so a key can get twenty times its limit. The two numbers per key move into a shared store that every server asks, with the refill and decision done as one atomic step. On one server, use a lock per key behind a small guard on the map, so different keys never wait for each other.Learn more Design a rate limiter · The bouncer at the door
10Design a logger: levels, several destinations, and a different format per destination.
A
Levelinteger enum and aLoggerthat drops anything under its own threshold, then starts a chain of handlers. EachHandlerhas its own level and its ownFormatter, writes the line if the record's level is high enough, and always passes the record to the next handler. Console, file and in-memory are three subclasses, and the in-memory one is what tests read.Ask first: which levels and in what order, where do messages go, does each place filter and format on its own, who gets the logger. It is a chain of responsibility where nobody ends the line, because the console writing a warning must not stop the file from seeing it. The formatter is a strategy, so a new shape is a new class. With the logger at INFO, a console at WARNING (30) and a file at DEBUG (10), an INFO message (20) reaches the file only and a DEBUG message (10) reaches nobody.
Follow-up Make it a singleton. Then: writes to a slow disk are stalling our request threads, and two threads are tangling lines in one file.
A singleton works but is shared mutable state: one test's handlers are still there for the next, so tests that pass alone fail together. Prefer a module-level instance or injecting the logger. For the slow disk, put a queue between caller and handler so the caller returns at once and a worker thread does the write, and say it needs a flush on exit and a bounded queue. For the tangled lines, hold one lock per handler around the whole line write.
Learn more Design a logger · Swap the rule, keep the class (strategy and injection)
11Design chess for two players online: the pieces, the board, the rules, and undo.
Five classes:
Board(which piece stands on which square),Piecesubclasses that each answermoves(board, square), aSliderpart that rook, bishop and queen share by composition,Moveas a command object withexecuteandundo, andGameholding the turn, the move number and the history. Legal moves are the pseudo-legal ones minus any that leave your own king attacked.Polymorphism removes every
if kind == ...ladder: a new piece is a new class and nothing else is edited. Validation is mechanical: execute each candidate, ask whether your king is attacked, undo it. A bishop with 9 pseudo-legal squares that is pinned against its king has 0 legal moves. BecauseMoveremembers the piece it captured, the sameundoserves validation and the take-back button. Game status (playing, check, checkmate, stalemate) is worked out from the legal moves, never stored, so it cannot go stale.Follow-up Two players are online and both press a move at the same instant. How do you keep one game consistent?
Moves are applied by one owner, one at a time, here a lock inside
Game.play. Every move carries the move number the player last saw, and if it does not equal the game's current number it raises a stale-move error and the client refetches the position and retries. The same version check works when the game lives in a database shared by many servers.Learn more Design chess · Has-a beats is-a (composition and polymorphism)
12Design snake and ladder for two to four players, and make it testable.
A
Boardholds one map of jumps, because a snake and a ladder are the same thing, a jump from one square to another, and it refuses bad jumps when built: one from the last square, two on one square, or one landing on another jump's start. The dice are an injected strategy behind one call,roll, so a test hands in a fixed list and play uses a seeded random. Adequeof names is the turn order, and the game loop returns the winner.A game that calls the random function inside itself plays differently every run, so no test can say what should happen. Injected dice let a fixed sequence hit a ladder, the exact-roll rule (a roll past the last square leaves the player where they are) and a win on purpose. A seed makes random play replayable. In the lesson, 10,000 seeded solo games on a 100-square board averaged 39.2 turns to land exactly on 100.
Follow-up Add this rule: a six gives another turn, and three sixes in a row forfeit the turn. Then say what changes when each player's roll arrives over the network.
The rule is one subclass overriding the turn method, with a streak counter and the square where the streak began. The board and the dice do not change. For the network, give the game one owner: rolls go into a thread-safe inbox, and one worker applies them in arrival order, replying
not your turnto any sender who is not at the front of the queue. Only that worker touches the game, so no lock is needed.Learn more Design snake and ladder · Swap the rule, keep the class