How to approach an LLD interview
A step-by-step method for low-level design interviews: OOD discussion vs machine coding, timings, finding classes, choosing patterns, clean code, tests and concurrency.
On this page
The problem: a blank editor and one vague sentence
The interviewer says one sentence: "Design a system to book meeting rooms." A common first reaction is to start typing classes straight away. Twenty minutes later there is a Room class with eight getters, a BookingManager that does everything, no code that runs, and the interviewer asks: "What happens if two people book the same room at the same moment?" There is no time left to answer well.
The candidate knew enough to pass. What failed was the process: no agreed scope, no plan for the time, nothing running at the end. Low-level design (LLD) interviews test whether you can turn a vague request into a small, correct, extensible object model and working code. This page gives you a repeatable method for that, then applies it end to end to the meeting-room problem, with complete Java and Python code.
Two formats, two different jobs
"LLD interview" covers two rounds that look alike but are graded differently. Ask the recruiter which one you have.
Where the time goes in each format
| OOD discussion | Machine-coding round | |
|---|---|---|
| Length | 45–60 minutes | 60–120 minutes (90 is typical) |
| Where | Whiteboard, shared doc or plain editor | Your own IDE; code must compile and run |
| You produce | Requirements, class diagram, key method bodies, discussion of extensions | A complete working program with a demo (a main or tests), often submitted afterwards |
| Interviewer's role | Active: asks questions and pushes on design choices | Often silent while you code, then reviews and asks for a change |
| Typical problems | Parking lot, elevator, library, chess | Splitwise, snake and ladder, rate limiter, LRU cache, cab booking |
| Biggest risk | Drawing classes without explaining why | Running out of time with nothing that runs |
OOD means object-oriented design: modelling a problem as classes that hold data and behaviour. Many large tech companies use the discussion format; many product companies (especially in India's startup ecosystem) use machine coding. Some do a hybrid: 15 minutes of design, then 30 of code.
The method, step by step
The same seven steps work in both formats; only the time spent on each changes.
| Step | What you do | OOD (45 min) | Machine coding (90 min) |
|---|---|---|---|
| 1. Clarify | Ask questions, write the agreed scope and what's out | 5 min | 10 min |
| 2. Entities | Nouns → classes, verbs → methods | 5 min | 5 min |
| 3. Class design | Responsibilities, relationships, interfaces for what varies | 10–15 min | 10 min |
| 4. Core flows | Signatures and bodies of the 2–3 main methods | 10–15 min | (part of coding) |
| 5. Code | Models → services → driver | (key methods only) | 45–50 min |
| 6. Test | Happy path, edge cases, a concurrency test | 2 min (talk) | 10 min |
| 7. Extend | Answer "what if…" without rewriting | 5–10 min | 10 min |
Say the plan out loud at the start: "I'll spend five minutes on requirements, sketch the classes, then code the booking flow first." Interviewers grade time management, and a stated plan lets them steer you early.
Step 1: clarify the requirements
Ask questions that change the design, not ones that only change the UI. For the meeting-room booker:
- Scale and shape: how many rooms and buildings? (In-memory is fine for an interview; say you'd swap in a database.)
- The core rule: can bookings overlap? Is 9:00–10:00 next to 10:00–11:00 allowed? (Yes: treat slots as half-open,
[start, end), meaning the start is included and the end is not.) - Who can do what: can anyone cancel, or only the organiser?
- Choice: does the user pick a room, or does the system pick one for a group size?
- Concurrency: can two people book at once? (Always assume yes.)
- Out of scope: recurring meetings, calendar invites, payments, UI.
Write the agreed list where the interviewer can see it. It becomes your checklist and your defence: when asked "what about recurring meetings?", you can say "out of scope, but here's how the design would absorb it".
Step 2: find the entities
Underline the nouns in the requirements. A noun that has its own data and behaviour becomes a class; a noun that only describes another one becomes a field; a noun nothing uses is dropped. Verbs become methods on the class that owns the data they change.
Nouns become classes or fields, then connect them
A useful test: "who owns this data?" The overlap check needs a room's bookings, so it lives next to them (in the service, per room), not in User. And small immutable concepts such as a time slot deserve their own value object: a tiny class compared by its contents, not its identity, that validates itself (start before end) and answers questions (overlaps). It removes a whole class of bugs from everywhere else.
Step 3: the class design
| Class | Responsibility | Why it exists |
|---|---|---|
Room | Id and capacity | An entity with identity |
Slot | Start, end, overlaps() | Value object; one correct overlap rule |
Booking | Who booked which room for which slot | The record we create and cancel |
BookingService | Book, find a room, cancel; owns the locks | The one entry point for callers |
RoomSelectionStrategy | Picks one room from free candidates | The rule most likely to change |
Keep the number of classes small. Five well-named classes with clear jobs beat fifteen with vague ones. The only interface here is for the thing that varies: how to choose a room (smallest that fits, nearest to the user's desk, the one with a video screen).
Choosing patterns without forcing them
Interviewers reward patterns that solve a stated problem and penalise patterns used to show off. Name the signal first, then the pattern:
| Signal in the requirements | Pattern | Example |
|---|---|---|
| "Several ways to do the same job, chosen at run time" | Strategy | Pricing, room choice, split types, eviction |
| "Notify these people when X happens" | Observer | Hold ready, price alert, game over |
| "Behaviour depends on the current status, with rules for moving between them" | State | Vending machine, order lifecycle, elevator |
| "Undo", "queue requests", "log every action" | Command | Text editor, game moves |
| "Many optional parameters" | Builder | A search query, a pizza order |
| "Create one of several types from input" | Factory | Vehicle from a type string |
The worked example: complete code
The code below is what a strong 90-minute submission looks like for the agreed scope. Notice the order it is written in: models (value objects and entities, with validation), then the interface for what varies, then the service, then a driver that exercises every flow, including the edge cases and a race.
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
// ---------- models ----------
final class Room {
private final String id;
private final int capacity;
Room(String id, int capacity) {
if (capacity <= 0) throw new IllegalArgumentException("capacity must be positive");
this.id = id; this.capacity = capacity;
}
String id() { return id; }
int capacity() { return capacity; }
}
/** A half-open time slot [start, end): a booking ending at 10:00 does not clash with one starting at 10:00. */
record Slot(LocalDateTime start, LocalDateTime end) {
Slot {
if (!start.isBefore(end)) throw new IllegalArgumentException("start must be before end");
}
boolean overlaps(Slot o) { return start.isBefore(o.end) && o.start.isBefore(end); }
}
record Booking(long id, String roomId, String userId, Slot slot) {}
class BookingConflictException extends RuntimeException {
BookingConflictException(String msg) { super(msg); }
}
// ---------- what varies: how to pick a room ----------
interface RoomSelectionStrategy {
/** Choose one room from candidates that are already free and big enough. */
Optional<Room> choose(List<Room> candidates, int attendees);
}
class SmallestFitStrategy implements RoomSelectionStrategy {
public Optional<Room> choose(List<Room> candidates, int attendees) {
return candidates.stream().min(Comparator.comparingInt(Room::capacity));
}
}
// ---------- the service ----------
class BookingService {
private final Map<String, Room> rooms = new LinkedHashMap<>(); // filled at start-up only
private final Map<String, List<Booking>> bookingsByRoom = new ConcurrentHashMap<>();
private final Map<Long, Booking> bookingsById = new ConcurrentHashMap<>();
private final AtomicLong nextId = new AtomicLong(1);
private final RoomSelectionStrategy strategy;
BookingService(RoomSelectionStrategy strategy) { this.strategy = Objects.requireNonNull(strategy); }
void addRoom(Room room) {
rooms.put(room.id(), room);
bookingsByRoom.put(room.id(), new ArrayList<>());
}
/** Check and insert happen under the room's lock, so two callers cannot both win the same slot. */
Booking book(String roomId, String userId, Slot slot) {
List<Booking> list = bookingsByRoom.get(roomId);
if (list == null) throw new NoSuchElementException("no room " + roomId);
synchronized (list) {
for (Booking b : list) {
if (b.slot().overlaps(slot)) throw new BookingConflictException(roomId + " is taken at that time");
}
Booking booking = new Booking(nextId.getAndIncrement(), roomId, userId, slot);
list.add(booking);
bookingsById.put(booking.id(), booking);
return booking;
}
}
/** Find a free room for the group using the strategy, then book it (retrying if someone beats us). */
Booking bookAny(String userId, int attendees, Slot slot) {
for (int attempt = 0; attempt < 3; attempt++) {
List<Room> free = new ArrayList<>();
for (Room r : rooms.values()) {
if (r.capacity() >= attendees && isFree(r.id(), slot)) free.add(r);
}
Room chosen = strategy.choose(free, attendees)
.orElseThrow(() -> new BookingConflictException("no room fits " + attendees + " people"));
try {
return book(chosen.id(), userId, slot);
} catch (BookingConflictException raced) {
// another thread took it between isFree() and book(); look again
}
}
throw new BookingConflictException("rooms keep filling up, try again");
}
boolean isFree(String roomId, Slot slot) {
List<Booking> list = bookingsByRoom.get(roomId);
synchronized (list) {
return list.stream().noneMatch(b -> b.slot().overlaps(slot));
}
}
void cancel(long bookingId, String userId) {
Booking b = bookingsById.get(bookingId);
if (b == null) throw new NoSuchElementException("no booking " + bookingId);
if (!b.userId().equals(userId)) throw new SecurityException("only the organiser can cancel");
if (!bookingsById.remove(bookingId, b)) return; // a concurrent cancel already did it
List<Booking> list = bookingsByRoom.get(b.roomId());
synchronized (list) { list.remove(b); }
}
List<Booking> bookingsFor(String roomId) {
List<Booking> list = bookingsByRoom.get(roomId);
synchronized (list) { return List.copyOf(list); }
}
}
// ---------- driver ----------
public class RoomBooking {
static LocalDateTime at(int hour, int minute) { return LocalDateTime.of(2026, 11, 18, hour, minute); }
public static void main(String[] args) throws Exception {
BookingService svc = new BookingService(new SmallestFitStrategy());
svc.addRoom(new Room("Ada", 4));
svc.addRoom(new Room("Turing", 10));
Booking b1 = svc.book("Ada", "priya", new Slot(at(9, 0), at(10, 0)));
System.out.println("booked " + b1);
Booking b2 = svc.book("Ada", "arjun", new Slot(at(10, 0), at(11, 0))); // touches, no overlap
System.out.println("booked " + b2);
try {
svc.book("Ada", "sam", new Slot(at(9, 30), at(10, 30)));
} catch (BookingConflictException e) {
System.out.println("rejected: " + e.getMessage());
}
Booking b3 = svc.bookAny("sam", 3, new Slot(at(9, 30), at(10, 30))); // Ada busy, so Turing
System.out.println("bookAny chose " + b3.roomId());
svc.cancel(b1.id(), "priya");
System.out.println("Ada after cancel: " + svc.bookingsFor("Ada").size() + " booking(s)");
// two threads race for the same slot: exactly one must win
Slot contested = new Slot(at(14, 0), at(15, 0));
int[] wins = {0};
Runnable attempt = () -> {
try { svc.book("Turing", Thread.currentThread().getName(), contested); synchronized (wins) { wins[0]++; } }
catch (BookingConflictException ignored) { }
};
List<Thread> threads = new ArrayList<>();
for (int i = 0; i < 8; i++) { Thread t = new Thread(attempt, "t" + i); threads.add(t); t.start(); }
for (Thread t : threads) t.join();
System.out.println("winners for 14:00 on Turing: " + wins[0]);
}
}import itertools
import threading
from abc import ABC, abstractmethod
from dataclasses import dataclass
from datetime import datetime
# ---------- models ----------
@dataclass(frozen=True)
class Room:
id: str
capacity: int
def __post_init__(self):
if self.capacity <= 0:
raise ValueError("capacity must be positive")
@dataclass(frozen=True)
class Slot:
"""A half-open slot [start, end): 9-10 and 10-11 do not clash."""
start: datetime
end: datetime
def __post_init__(self):
if self.start >= self.end:
raise ValueError("start must be before end")
def overlaps(self, other: "Slot") -> bool:
return self.start < other.end and other.start < self.end
@dataclass(frozen=True)
class Booking:
id: int
room_id: str
user_id: str
slot: Slot
class BookingConflict(Exception):
pass
# ---------- what varies: how to pick a room ----------
class RoomSelectionStrategy(ABC):
@abstractmethod
def choose(self, candidates: list[Room], attendees: int) -> Room | None: ...
class SmallestFit(RoomSelectionStrategy):
def choose(self, candidates, attendees):
return min(candidates, key=lambda r: r.capacity, default=None)
# ---------- the service ----------
class BookingService:
def __init__(self, strategy: RoomSelectionStrategy):
self._strategy = strategy
self._rooms: dict[str, Room] = {}
self._by_room: dict[str, list[Booking]] = {}
self._locks: dict[str, threading.Lock] = {}
self._by_id: dict[int, Booking] = {}
self._ids = itertools.count(1)
self._id_lock = threading.Lock() # ids are shared by all rooms
def add_room(self, room: Room) -> None: # called at start-up, before any booking
self._rooms[room.id] = room
self._by_room[room.id] = []
self._locks[room.id] = threading.Lock()
def book(self, room_id: str, user_id: str, slot: Slot) -> Booking:
if room_id not in self._rooms:
raise KeyError(f"no room {room_id}")
with self._locks[room_id]: # check and insert as one step
if any(b.slot.overlaps(slot) for b in self._by_room[room_id]):
raise BookingConflict(f"{room_id} is taken at that time")
with self._id_lock:
booking_id = next(self._ids)
booking = Booking(booking_id, room_id, user_id, slot)
self._by_room[room_id].append(booking)
self._by_id[booking.id] = booking
return booking
def is_free(self, room_id: str, slot: Slot) -> bool:
with self._locks[room_id]:
return not any(b.slot.overlaps(slot) for b in self._by_room[room_id])
def book_any(self, user_id: str, attendees: int, slot: Slot) -> Booking:
for _ in range(3):
free = [r for r in self._rooms.values()
if r.capacity >= attendees and self.is_free(r.id, slot)]
chosen = self._strategy.choose(free, attendees)
if chosen is None:
raise BookingConflict(f"no room fits {attendees} people")
try:
return self.book(chosen.id, user_id, slot)
except BookingConflict:
continue # someone took it between is_free and book
raise BookingConflict("rooms keep filling up, try again")
def cancel(self, booking_id: int, user_id: str) -> None:
b = self._by_id.get(booking_id)
if b is None:
raise KeyError(f"no booking {booking_id}")
if b.user_id != user_id:
raise PermissionError("only the organiser can cancel")
with self._locks[b.room_id]:
if self._by_id.pop(booking_id, None) is not None: # a concurrent cancel may have won
self._by_room[b.room_id].remove(b)
def bookings_for(self, room_id: str) -> list[Booking]:
with self._locks[room_id]:
return list(self._by_room[room_id])
# ---------- driver ----------
def at(hour: int, minute: int = 0) -> datetime:
return datetime(2026, 11, 18, hour, minute)
if __name__ == "__main__":
svc = BookingService(SmallestFit())
svc.add_room(Room("Ada", 4))
svc.add_room(Room("Turing", 10))
b1 = svc.book("Ada", "priya", Slot(at(9), at(10)))
print("booked", b1)
b2 = svc.book("Ada", "arjun", Slot(at(10), at(11))) # touches, no overlap
print("booked", b2)
try:
svc.book("Ada", "sam", Slot(at(9, 30), at(10, 30)))
except BookingConflict as e:
print("rejected:", e)
b3 = svc.book_any("sam", 3, Slot(at(9, 30), at(10, 30))) # Ada busy, so Turing
print("book_any chose", b3.room_id)
svc.cancel(b1.id, "priya")
print("Ada after cancel:", len(svc.bookings_for("Ada")), "booking(s)")
# eight threads race for one slot: exactly one must win
contested, wins, wins_lock = Slot(at(14), at(15)), [0], threading.Lock()
def attempt(name):
try:
svc.book("Turing", name, contested)
with wins_lock:
wins[0] += 1
except BookingConflict:
pass
threads = [threading.Thread(target=attempt, args=(f"t{i}",)) for i in range(8)]
for t in threads:
t.start()
for t in threads:
t.join()
print("winners for 14:00 on Turing:", wins[0])Points worth saying out loud while you write it:
- The overlap rule lives in one place (
Slot.overlaps), and the half-open convention is a comment, not a guess. - Errors are exceptions with clear names (
BookingConflictException), notnullorfalsethat callers forget to check. - The strategy picks; the service enforces.
bookAnyasks the strategy for a room, then books it through the same lockedbookmethod, and retries if another request took it in between. - The driver proves it: a normal booking, a touching booking that must succeed, an overlap that must fail, a cancel, and eight threads racing for one slot with exactly one winner.
Writing clean code under time pressure
- No frameworks, no database. Use in-memory maps ("repositories") behind the service, and say a real system would put a database behind the same methods.
- Names over comments.
findFreeRoomneeds no comment;processneeds a paragraph. - Immutable where you can. Records in Java, frozen dataclasses in Python. Immutable objects can be shared between threads safely.
- Validate at the edges. Constructors reject bad input (capacity 0, start after end), so the rest of the code can trust its data.
- Skip the ceremony. You do not need getters and setters for every field, a
Managerper class, or JavaDoc on every method. Spend the time on the hard rule. - Keep it compiling. Run the program every 10–15 minutes. A compile error found at minute 85 is a disaster; at minute 20 it is nothing.
Step 6: test it
In machine coding, the driver is your test suite; make it print results you can check at a glance. If time allows, add two or three real unit tests for the riskiest rule:
@Test
void touchingSlotsDoNotClash() {
BookingService svc = new BookingService(new SmallestFitStrategy());
svc.addRoom(new Room("Ada", 4));
svc.book("Ada", "a", new Slot(at(9, 0), at(10, 0)));
assertDoesNotThrow(() -> svc.book("Ada", "b", new Slot(at(10, 0), at(11, 0))));
assertThrows(BookingConflictException.class,
() -> svc.book("Ada", "c", new Slot(at(9, 59), at(10, 30))));
}import pytest
def test_touching_slots_do_not_clash():
svc = BookingService(SmallestFit())
svc.add_room(Room("Ada", 4))
svc.book("Ada", "a", Slot(at(9), at(10)))
svc.book("Ada", "b", Slot(at(10), at(11))) # must not raise
with pytest.raises(BookingConflict):
svc.book("Ada", "c", Slot(at(9, 59), at(10, 30)))The edge cases interviewers look for: boundaries (exactly touching slots, capacity exactly equal to the group), invalid input (end before start, unknown room), permission (cancelling someone else's booking), and the concurrent case.
Step 7 and beyond: concurrency
Almost every LLD problem has one shared, scarce thing: the last parking spot, the last seat, a room at 14:00, a user's balance. Find it, then say how you protect it.
Two requests, one slot: check-then-act and the fix
The bug pattern is always check-then-act: read a condition ("is it free?"), then act on it ("insert a booking") as two separate steps. Another thread can change the world in between. The fixes, from smallest to largest scope:
| Fix | How | Good for | Catch |
|---|---|---|---|
| Lock per resource | synchronized (roomBookings) / one Lock per room | One process, in-memory model | Different rooms don't block each other; must lock in a fixed order if you ever need two |
| One global lock | synchronized on every service method | Simplest correct answer | Serialises everything; fine for an interview, slow at scale |
| Atomic operations | ConcurrentHashMap.putIfAbsent, AtomicInteger.compareAndSet | Single values (a seat id → holder) | Doesn't cover multi-step rules like interval overlap |
| Database constraint | Unique index, or SELECT … FOR UPDATE, or an exclusion constraint on time ranges (Postgres) | Several app servers | The real answer once more than one process exists |
Python threads and the GIL
CPython's global interpreter lock (GIL) lets only one thread run Python bytecode at a time, but it can switch threads between any two bytecodes, so check-then-act is just as broken in Python as in Java. x += 1 on a shared counter is several bytecodes and can lose updates. Use threading.Lock for multi-step rules. Python 3.13 also ships an optional free-threaded build without the GIL, which makes explicit locking even more important.
What interviewers grade
| Area | Strong signal | Weak signal |
|---|---|---|
| Requirements | Asks questions that change the design; states what is out of scope | Starts coding immediately, or asks 20 questions about the UI |
| Modelling | Few classes with one clear job each; value objects; enums for fixed sets | God class; anaemic classes that are only getters |
| Extensibility | Interfaces exactly where change is expected; can add a feature by adding a class | Patterns everywhere, or none where they're obviously needed |
| Code quality | Readable names, small methods, validation, exceptions, immutability | Magic numbers, copy-pasted blocks, null returns |
| Correctness | Demo runs; edge cases handled; overlap and money rules right | Doesn't compile; happy path only |
| Concurrency | Names the race and the narrowest correct lock | "It's single-threaded" without being told so |
| Communication | Explains trade-offs as they go; takes hints well | Silent for 40 minutes; defends a bad choice |
Common mistakes
- Designing the database instead of the objects. Tables come later, if at all. Start with behaviour.
- Building everything at once. Get one flow working end to end, then widen.
- Using inheritance for variation that is data.
WeekendTicket extends Ticketwhen a pricing rule would do. - Floating-point money.
0.1 + 0.2 != 0.3. Use integer cents (long) orBigDecimal/Decimal. - Leaking internals. Returning your internal
Listlets callers modify it without the lock; return a copy or an unmodifiable view. - Ignoring time. Calling
Instant.now()deep inside logic makes it untestable; pass in aClock(Java) or anowfunction (Python) so tests can control time.
When not to follow the full method
- A 20-minute question inside another round. Skip the diagram; state three requirements, write the core class, mention the race.
- The interviewer leads. If they hand you requirements and a skeleton, don't re-clarify everything: confirm the two or three ambiguous points and start.
- A pure algorithm hidden as LLD. "Design an LRU cache" is mostly about the data structure; the class design is small. Spend the time on getting O(1) right (see Design an LRU cache).
In the interview
"Design a car rental system." Spend five minutes: write 4–5 requirements with one out-of-scope item, list the classes with one responsibility each, name the one or two things that vary, and name the race.
Compare with our answer
| Class | Responsibility |
|---|---|
Car | Id, category (enum: ECONOMY, SUV…), branch, daily rate |
Branch | Location and the cars stationed there |
Reservation | Customer, car, date range (a half-open value object, like Slot), status |
RentalService | Search available cars, reserve, pick up, return, cancel |
PricingStrategy | Daily, weekly discount, weekend rate |
Requirements to agree: search by branch, category and dates; reserve a specific car; pick up and return (late return costs extra); cancel before pickup. Out of scope: payments, insurance, loyalty points.
A strong answer mentions: a date-range value object with one overlap rule · reservations checked and inserted under a lock per car (the race is two customers, one car, overlapping dates) · pricing as a strategy, chosen per branch or season · status as an enum (RESERVED → PICKED_UP → RETURNED / CANCELLED) with legal transitions checked · money in integer cents or a decimal type.
A candidate's booking method passes their demo. Find at least four problems.
class BookingService {
private final Map<String, List<Booking>> bookings = new HashMap<>();
private long nextId = 1;
Booking book(String roomId, String user, Slot slot) {
List<Booking> list = bookings.get(roomId);
for (Booking b : list)
if (b.slot().start().equals(slot.start())) throw new BookingConflictException("taken");
Booking bk = new Booking(nextId++, roomId, user, slot);
list.add(bk);
return bk;
}
}class BookingService:
def __init__(self):
self.bookings = {} # room_id -> list[Booking]
self.next_id = 1
def book(self, room_id, user, slot):
lst = self.bookings[room_id]
for b in lst:
if b.slot.start == slot.start:
raise BookingConflict("taken")
bk = Booking(self.next_id, room_id, user, slot)
self.next_id += 1
lst.append(bk)
return bkCompare with our answer
- Wrong overlap rule: only equal start times clash, so 9:00–10:00 and 9:30–10:30 both succeed. Use
start < other.end && other.start < end. - Check-then-act race: two threads both pass the loop and both append. Lock the room's list around check and insert.
nextId++/self.next_id += 1is not atomic: two bookings can get the same id. UseAtomicLongor take the id under a lock.- Unsafe collections:
HashMapandArrayList(or a list being appended while another thread iterates it) are not safe for concurrent use without a lock. - Unknown room crashes with a
NullPointerException/KeyErrorinstead of a clear error.
Booking book(String roomId, String user, Slot slot) {
List<Booking> list = bookings.get(roomId); // ConcurrentHashMap
if (list == null) throw new NoSuchElementException("no room " + roomId);
synchronized (list) {
for (Booking b : list)
if (b.slot().overlaps(slot)) throw new BookingConflictException(roomId + " is taken");
Booking bk = new Booking(nextId.getAndIncrement(), roomId, user, slot); // AtomicLong
list.add(bk);
return bk;
}
}def book(self, room_id, user, slot):
if room_id not in self.bookings:
raise KeyError(f"no room {room_id}")
with self.locks[room_id]: # one threading.Lock per room
if any(b.slot.overlaps(slot) for b in self.bookings[room_id]):
raise BookingConflict(f"{room_id} is taken")
with self.id_lock:
booking_id = self.next_id
self.next_id += 1
bk = Booking(booking_id, room_id, user, slot)
self.bookings[room_id].append(bk)
return bkA strong answer mentions: the interval overlap formula · check-then-act and a per-room lock · a non-atomic id counter · thread-unsafe collections · a clear error for an unknown room.
- Two formats: OOD discussion (45–60 min, design + key methods) vs machine coding (60–120 min, code must run). Ask which.
- Seven steps: clarify → entities → class design → core flows → code → test → extend. Say the time plan out loud.
- Entities: nouns with data and behaviour → classes; describing nouns → fields; verbs → methods on the owner of the data.
- Value objects (
Slot,Money,DateRange) hold one rule each and remove bugs everywhere else. - Patterns only for a stated signal: varies → Strategy; notify → Observer; status rules → State; undo → Command. No Singleton by reflex.
- Code order: models → interface for what varies → service → driver. Compile every 10–15 minutes; working beats complete.
- Concurrency: find the scarce shared thing; check-then-act is the bug; lock per resource; database constraint across servers.
- Money in integer cents or decimals; time injected through a clock so tests can control it.
1. You have a 90-minute machine-coding round for "design Splitwise". At minute 60 you have clean classes for five features but nothing runs yet. What is the best move?
Machine coding is graded on working code. Two flows that run beat five that might not compile. Add features one at a time, re-running the demo after each.
2. Requirements say: "Members borrow books; each book has a title and an ISBN; the shelf colour is printed on the label." Which modelling is best?
Nouns with data and behaviour become classes; descriptive nouns become fields; nouns nothing uses are dropped. Turning every noun into a class bloats the design, and strings lose type safety.
3. A candidate makes BookingService a Singleton "because the system only has one". What is the main objection?
A Singleton is global state with a fancy name: tests leak into each other and dependencies become invisible. Creating one instance and injecting it gives "only one" without those costs.
4. Two requests call if (isFree(room, slot)) add(booking) at the same moment for the same room and time. What happens, and what is the fix?
This is check-then-act. Without a lock, both checks can pass before either insert. Locking the room's bookings around both steps leaves exactly one winner. A ConcurrentModificationException is not guaranteed and is not a correctness mechanism.
5. Your in-memory booking service uses synchronized per room. The interviewer says it will run on three servers sharing one Postgres database. What should change?
In-process locks only protect one process. With several servers, the shared database must enforce the rule. Sending everything to one server works but throws away the other two and creates a single point of failure.
6. Which situation is the strongest reason to introduce an interface in an LLD design?
Interfaces earn their place where behaviour varies: here room choice, so a RoomSelectionStrategy. Interfaces everywhere is pattern-stuffing, which interviewers mark down.
7. A booking rule uses LocalDateTime.now() inside cancel() to check "no cancellations within 1 hour of the start". Why might an interviewer push back?
Reading the real clock deep inside logic makes time-based rules untestable. Passing a Clock (or a function returning the time) lets a test set "10 minutes before the start" and check the result.
Score 60% or more and the lesson is marked complete.