Low-Level Design Interview Questions with Code
Last updated 2026-11-19
Low-level design (LLD) rounds ask you to turn a short problem statement, such as a parking lot or an LRU cache, into classes, relationships and working code. Interviewers watch how you pick entities, where you put behaviour, how you apply a pattern when it earns its place and whether the design survives a new requirement. This page works through the common problems with class outlines and runnable code.
The principles come from SOLID questions and the patterns from design patterns questions. For the process, read how to crack a low-level design interview; for scale-level design see system design questions.
| Format | Class design plus code, 45 to 60 minutes |
|---|---|
| Code in | Java and Python |
| Level | Medium to hard |
A six-step approach
Clarify requirements and scope. List the nouns as candidate classes and the verbs as methods. Draw relationships: which class owns which, and which are is-a or has-a. Identify the parts that will vary, and put an interface there. Write the core code for the main flow. Finally walk through one extension, for example "add a new vehicle type", to show the design bends without breaking.
Mistakes that cost marks
- Starting to code before agreeing on requirements and the main use cases.
- One huge class that does everything, which shows up as a God object.
- Patterns forced in where a simple method would do.
- Ignoring concurrency when two users can act on the same resource, such as the same seat.
- No error handling for the obvious failures: lot full, unknown ticket, invalid move.
Low-Level Design Interview Questions with Code: questions with worked answers
1 Design a parking lot: classes, relationships and core code.
hardEntities: ParkingLot (owns slots and active tickets), Slot (id, type), Vehicle type (enum), Ticket (id, slot, plate, entry time) and a PricingStrategy. Relationships: the lot has many slots (composition), a ticket references one slot, and pricing is injected so a new rule needs no change to the lot. park() takes a free slot of the matching type and issues a ticket; exit() releases the slot and computes the fee. Free slots are kept in a queue per type, giving O(1) allocation. Methods are synchronised so two cars cannot get the same slot. Extension: a new vehicle type adds an enum value and slots; a multi-floor lot adds a Floor class that holds the per-type queues.
javaimport java.time.*; import java.util.*; enum VehicleType { BIKE, CAR, TRUCK } class Slot { final int id; final VehicleType type; Slot(int id, VehicleType type) { this.id = id; this.type = type; } } class Ticket { final String id; final Slot slot; final String plate; final Instant entry; Ticket(String id, Slot s, String plate, Instant e) { this.id = id; slot = s; this.plate = plate; entry = e; } } interface PricingStrategy { long fee(VehicleType t, Duration d); } class HourlyPricing implements PricingStrategy { public long fee(VehicleType t, Duration d) { long hours = Math.max(1, (d.toMinutes() + 59) / 60); long rate = switch (t) { case BIKE -> 10; case CAR -> 30; case TRUCK -> 60; }; return hours * rate; } } class ParkingLot { private final Map<VehicleType, Deque<Slot>> free = new EnumMap<>(VehicleType.class); private final Map<String, Ticket> active = new HashMap<>(); private final PricingStrategy pricing; private int seq = 0; ParkingLot(List<Slot> slots, PricingStrategy p) { pricing = p; for (VehicleType t : VehicleType.values()) free.put(t, new ArrayDeque<>()); for (Slot s : slots) free.get(s.type).add(s); } synchronized Ticket park(String plate, VehicleType t) { Slot s = free.get(t).poll(); if (s == null) throw new IllegalStateException("lot full for " + t); Ticket k = new Ticket("T" + (++seq), s, plate, Instant.now()); active.put(k.id, k); return k; } synchronized long exit(String ticketId) { Ticket k = active.remove(ticketId); if (k == null) throw new IllegalArgumentException("unknown ticket"); free.get(k.slot.type).add(k.slot); return pricing.fee(k.slot.type, Duration.between(k.entry, Instant.now())); } }2 Implement an LRU cache with O(1) get and put.
mediumCombine a hash map for O(1) lookup with an ordering structure that moves an entry to the most-recent end on every access and removes the least-recent entry on overflow. The classic build is a hash map from key to node in a doubly linked list. In Python, OrderedDict provides both, with move_to_end and popitem(last=False). Space is O(capacity). In Java, a LinkedHashMap constructed with accessOrder true and an overridden removeEldestEntry does the same. Note that the cache is not thread-safe as written; wrap operations in a lock for concurrent use.
pythonfrom collections import OrderedDict class LRUCache: def __init__(self, capacity): self.cap = capacity self.d = OrderedDict() def get(self, key): if key not in self.d: return -1 self.d.move_to_end(key) return self.d[key] def put(self, key, value): if key in self.d: self.d.move_to_end(key) self.d[key] = value if len(self.d) > self.cap: self.d.popitem(last=False) # evict least recently used3 Design Tic-Tac-Toe so that checking a win is O(1) per move.
mediumEntities: Board (size n), Player and Game. Instead of scanning the board after each move, keep counters: one per row, one per column and two for the diagonals. Player 1 adds +1 and player 2 adds -1; if any counter reaches n in absolute value after a move, that player has won. Each move touches at most four counters, so a win check is O(1) and space is O(n). A draw is detected when n squared moves have been made. Validate that the cell is empty and the game is not over.
pythonclass TicTacToe: def __init__(self, n): self.n = n; self.rows = [0]*n; self.cols = [0]*n self.diag = 0; self.anti = 0 def move(self, r, c, player): # player is 1 or 2 d = 1 if player == 1 else -1 self.rows[r] += d; self.cols[c] += d if r == c: self.diag += d if r + c == self.n - 1: self.anti += d hit = (abs(self.rows[r]), abs(self.cols[c]), abs(self.diag), abs(self.anti)) return player if self.n in hit else 04 Design a vending machine using the State pattern.
hardStates: Idle, HasMoney, Dispensing and OutOfStock. The VendingMachine context holds the current state, an Inventory and the inserted amount, and delegates insertMoney, selectProduct and cancel to the state. In Idle, insertMoney moves to HasMoney. In HasMoney, selectProduct checks stock and price: if enough, it moves to Dispensing, dispenses, returns change and goes back to Idle; if not, it reports the shortfall. Each state class owns its legal transitions, so illegal actions such as selecting a product with no money are rejected in one place instead of in nested ifs. Trade-off: more classes, but adding a state such as Maintenance does not touch the others. Money handling should use integer paise, not floating point.
5 Design an elevator system.
hardEntities: Elevator (current floor, direction, state, a set of stops), Request (internal button press or external hall call with direction) and a Dispatcher that assigns requests. Each elevator serves stops with the SCAN approach: keep moving in the current direction, stopping at requested floors in that direction, then reverse when none remain ahead. The dispatcher chooses an elevator by cost: prefer one already moving toward the caller in the same direction, otherwise the nearest idle one. The elevator is a state machine (Idle, MovingUp, MovingDown, DoorsOpen). Concerns: thread-safe request queues, a weight limit that skips stops when full, and a strategy interface for dispatching so the policy can be replaced.
6 Design seat booking for a movie ticket system. How do you stop double booking?
hardEntities: Show, Seat, Booking and Payment, with seat status Free, Held or Booked. The race is two users choosing the same seat. Make the claim atomic in the database: UPDATE seat SET status = 'HELD', held_by = ?, hold_until = now() + 5 min WHERE show_id = ? AND seat_id = ? AND (status = 'FREE' OR hold_until < now()). If one row is updated the user owns the hold, otherwise the seat is taken. On successful payment, set the status to Booked; a background job or the hold_until check releases expired holds. An in-memory lock works only on one server, so rely on the database or a Redis SET with NX and an expiry. Trade-off: a short hold reduces blocked seats but may expire during payment. Idempotency keys prevent a retried payment from booking twice.
7 Implement a token-bucket rate limiter class.
mediumThe bucket has a capacity and refills at a constant rate. On each request, add the tokens earned since the last check (capped at capacity), then take one token if available. This allows bursts up to capacity and a steady average rate. Store the tokens and the last refill time per client key, and guard updates with a lock. Time complexity is O(1) per call.
pythonimport time, threading class TokenBucket: def __init__(self, capacity, refill_per_sec): self.cap = capacity; self.rate = refill_per_sec self.tokens = capacity; self.last = time.monotonic() self.lock = threading.Lock() def allow(self): with self.lock: now = time.monotonic() self.tokens = min(self.cap, self.tokens + (now - self.last) * self.rate) self.last = now if self.tokens >= 1: self.tokens -= 1 return True return False8 Design the core of Splitwise: how do you simplify debts?
hardEntities: User, Group, Expense (payer, amount, split type and participants) and a Balance per pair or per user. Splits are strategies: Equal, Exact and Percent. For settlement, compute each person's net balance (total paid minus total owed), then repeatedly match the largest creditor with the largest debtor using two heaps. This yields at most n-1 payments for n people. It is not guaranteed minimal, since minimising the number of transactions is NP-hard, but it is simple and good in practice. Use integer paise and assign the rounding remainder to one participant so splits sum exactly.
pythonimport heapq def settle(net): # net[p] > 0: p is owed money; < 0: p owes cred = [(-v, p) for p, v in net.items() if v > 0] debt = [(v, p) for p, v in net.items() if v < 0] heapq.heapify(cred); heapq.heapify(debt); out = [] while cred and debt: c, cp = heapq.heappop(cred); d, dp = heapq.heappop(debt) amt = min(-c, -d) out.append((dp, cp, amt)) # dp pays cp if -c > amt: heapq.heappush(cred, (c + amt, cp)) if -d > amt: heapq.heappush(debt, (d + amt, dp)) return out9 Design a library management system. Outline the classes.
mediumEntities: Book (title, ISBN, authors) and BookCopy (copy id, status), since a library holds several physical copies; Member; Librarian; Loan (member, copy, issue date, due date, return date); Fine and a Catalog for search. A Member has many Loans, a Loan references one copy, and a Book has many copies, so the loan table is the many-to-many link. Rules such as maximum loans and fine per day belong in a policy object that can change without touching Loan. Search by title, author or ISBN is a Catalog responsibility, ideally behind an interface. Reservations add a queue per book and an Observer-style notification when a copy is returned.
10 Design a logging library.
mediumCore types: Logger, LogLevel (DEBUG to ERROR), Appender (console, file, remote) and Formatter. A logger holds a minimum level and a list of appenders, and log(level, msg) drops messages below the threshold, formats the rest and forwards to each appender. Appenders are a Strategy, so new destinations need no change to Logger. Loggers are often obtained from a factory by name and cached, which is the usual (and testable) form of the singleton idea. Production concerns: asynchronous logging through a queue so slow disks do not block requests, log rotation and thread safety.
11 How do you choose which design pattern to use in an LLD round?
mediumStart from what varies. A family of interchangeable algorithms, such as pricing or dispatch, suggests Strategy. An object whose behaviour depends on its state suggests State. A need to notify unknown listeners suggests Observer. Complex construction suggests Builder, and choosing among implementations at runtime suggests Factory. Say the pattern after stating the problem, and if a plain method is enough, say so. Over-patterning is a common reason candidates lose points. See design patterns questions.
12 How do you handle concurrency in an LLD design?
mediumIdentify the shared mutable state, such as slots, seats or counters, and decide the unit of locking. For a single process, use synchronized blocks or a lock per resource and keep critical sections short. Prefer concurrent collections and atomic classes for counters. For multiple servers, in-process locks are not enough: use database constraints, conditional updates or a distributed lock. Avoid deadlocks by taking locks in a consistent order. Mention that you would first make the design correct and then optimise.
13 How do you show that your design is extensible?
mediumPick a plausible change and walk through it. For a parking lot: a new vehicle type adds an enum value and slots; a new pricing rule adds one PricingStrategy class; electric vehicle charging adds a Slot subtype. If each change touches one place and no existing class changes, the design follows the open/closed principle. If a change forces edits to many classes, name the weakness and the refactor.
14 What should your final LLD answer include besides code?
mediumThe requirements you agreed, the list of entities with responsibilities, a text or drawn class diagram showing relationships, the main sequence for the key use case, the patterns used with reasons, the concurrency approach, error handling and a short list of known limitations and extensions. Interviewers often care more about the reasoning and trade-offs than the amount of code.
Frequently asked questions
Which language should I use for LLD rounds?
Use the one you are most fluent in, usually Java, Python or C++. The design matters more than syntax, but the code should compile or at least be convincing.
How is LLD different from system design?
LLD designs the classes inside one service. System design covers services, data stores and scale. See system design questions.
Do I need UML diagrams?
A simple box-and-arrow class diagram is enough. Show classes, key fields and methods, and relationships.
Which LLD problems are most common?
Parking lot, LRU cache, tic-tac-toe, vending machine, elevator, library system, BookMyShow and Splitwise appear most.
Related guides
More in CS Fundamentals Interview Questions
- Memory Management Interview Questions with Numericals
- Message Queue and Kafka Interview Questions
- Microservices Interview Questions and Answers
- MongoDB Interview Questions and Answers
- Network Security Interview Questions: Cryptography, Firewalls and Attacks
- Normalization Interview Questions with Worked Examples
- NoSQL Interview Questions and Answers
- OOPs Interview Questions and Answers
- Operating Systems Interview Questions with Worked Answers
- OSI Model Interview Questions: Layers, PDUs, Devices and Encapsulation
- Paging and Virtual Memory Interview Questions with Numericals
- Process and Thread Interview Questions with fork() Output Problems