LOW LEVEL DESIGN · MACHINE CODING
Low level design interview questions
The machine coding round, solved the way interviewers score it: requirements, the entities, a class diagram, the design patterns that fit, the core flows, thread safety and extension points, then the follow-up questions. Every problem ends with a full Java solution you can run.
New to LLD? Learn OOP, SOLID and the design patterns first, and read how to answer an LLD interview.
Classic object models
Entities, state machines and strategies: the questions asked in almost every machine coding round
- 1 Parking lotThe most common machine coding question, solved end to end: requirements, the entities, a class diagram, spot fitting rules, Strategy for spot choice and pricing, Observer for display boards, the entry and exit flows, two gates racing for one spot (compare-and-set), tickets used once, extension points and the follow-ups, with a full Java 17 solution.
- 2 Vending machineThe classic State pattern question: requirements, entities, why nested if statements break down, the Idle, HasMoney and Maintenance states with a transition table, the purchase flow, making change from a limited coin box (greedy, and when you need dynamic programming), restocking, low-stock alerts with Observer, thread safety and the follow-ups, with a full Java 17 solution.
- 3 Elevator systemA bank of elevators designed and coded step by step: requirements, hall calls versus car calls, the class diagram, splitting the problem into which car answers (a dispatch Strategy with a cost function) and in what order a car stops (the LOOK algorithm with two sorted sets), a tick-based control loop, many button threads feeding one loop, displays as observers, extensions and follow-ups, with full Java 17 code.
Data structures and services
Business rules, algorithms and thread safety inside one process
- 4 Splitwise (expense sharing)An expense sharing app designed and coded: requirements, users, groups, expenses and shares, why one net balance per user beats a pairwise ledger, equal, exact and percentage splits as Strategies chosen by a Factory, rounding without losing a paisa, debt simplification with two heaps, settling up, a lock per group, Observer notifications and the follow-ups, with full Java 17 code.
- 5 In-memory cache (TTL, LRU, LFU)A bounded key-value cache designed and coded: the API, entries with expiry times, eviction as a Strategy with O(1) LRU (an access-ordered set) and O(1) LFU (frequency buckets and a minimum), lazy plus background TTL expiry, the put and get flows, why a read-write lock does not help, one lock versus striping, removal listeners, an injectable clock for tests and the follow-ups, with full Java 17 code.
Scheduling and limits
Time, capacity and concurrency rules that interviewers love to extend
- 6 Rate limiterA rate limiter library designed and coded: per-key limits with rules per tier, the algorithm as a Strategy (token bucket, fixed window, sliding log, sliding window counter), the boundary burst that breaks fixed windows, a factory and computeIfAbsent for per-key state, a lock per key, retry-after answers, a hit counter with time buckets, and a full Java 17 solution.
- 7 In-memory file systemAn in-memory file system designed and coded: the Composite pattern with a sealed Node, Directory and File, path parsing with dot and dot-dot, mkdir -p, cd, pwd and ls, create, read and append, a session per terminal for the working directory, a small shell built with the Command pattern, a read-write lock, owner and others permissions as an extension, and a full Java 17 solution.
- 8 Meeting room schedulerA meeting room reservation system designed and coded: half-open intervals, a sorted map per room where one lowerEntry lookup detects any conflict, when an interval tree is worth it, room choice as a Strategy, booking and cancelling, listeners for invites, weekly series booked all or nothing, free slot search, a lock per room, and a full Java 17 solution.
- 9 Task scheduler (dependencies, workers)A task scheduler designed and coded: a task lifecycle as a state machine, dependencies as a DAG validated with Kahn's topological sort, unmet-dependency counters, a priority heap and a delay heap, a worker pool on one lock and condition, retries with exponential backoff, cancel with cascading to dependents, suspend and resume, and a full Java 17 solution.
- 10 Pub/sub and message queueA pub/sub library and message queue designed and coded: topics split into append-only partitions, a key partitioner for per-key ordering, consumer groups that fan out across groups and share work inside one, committed offsets as acks for at-least-once delivery, rebalancing and fencing stale consumers, idempotent consumers, push subscribers behind a bounded blocking queue for back-pressure, and full Java 17 code.
Everyday apps
Machine coding favourites: games, rentals, ordering and records
- 11 Snakes and laddersA favourite machine coding round, designed and coded: requirements, a board built and validated by a Builder, snakes and ladders as one Jump type, dice and finish rules as Strategies, a turn queue, an Observer for moves, turn checks for online play, and how the same model stretches to tic-tac-toe and the snake game, with a full Java 17 solution.
- 12 Vehicle rental systemA car rental system designed and coded: branches, vehicle types, half-open time ranges, a booking calendar per vehicle with a TreeMap neighbour check, search by availability, booking without double booking, pricing as a Strategy with a discount Decorator, a booking state machine, late and damage fees at return, and the follow-ups, with a full Java 17 solution.
- 13 Food ordering and billingA food delivery app designed and coded: restaurants and menus, a cart locked to one restaurant, an order state machine, billing with discounts as Strategies and tax rounded in paise, nearest-rider assignment with compare-and-set, Observer notifications, a most-ordered items tracker, and the follow-ups, with a full Java 17 solution.
- 14 Logger with multiple sinksA logging library designed and coded: levels with cheap filtering and lazy messages, per-name level overrides, a LogManager factory, formatters and sinks (console, file, remote with batching) as Strategies, a Chain of Responsibility of handlers, an async dispatcher with a bounded queue, block or drop on overflow, clean shutdown, and the follow-ups, with a full Java 17 solution.
- 15 Library managementA library system designed and coded: books versus physical copies, members with plans and limits, borrow, return and a FIFO hold queue per title, fines as a Strategy, keyword search with an inverted index, Observer notifications, lock ordering so borrowing never deadlocks, a race for the last copies, and the follow-ups, with a full Java 17 solution.
Infrastructure inside one process
Pools, breakers, tiny databases and history
- 16 Connection poolA bounded database connection pool designed and coded: min and max size, borrow with a timeout using a fair semaphore, a warm-first idle deque, validation on borrow and on return, a lease proxy whose close() gives the connection back, idle eviction down to the minimum, leak detection, permit safety on failure, a thread pool executor as the follow-up, and full Java 17 code.
- 17 Circuit breakerA circuit breaker designed and coded: the closed, open and half-open state machine, a count-based sliding window with an O(1) failure rate, a minimum number of calls before tripping, slow calls counted as failures, a lazy cool-down timer, a limited number of half-open trials under a race, fallbacks, retry with exponential backoff and full jitter, listeners and the follow-ups, with full Java 17 code.
- 18 In-memory SQL-like databaseA tiny SQL-like database designed and coded: typed schemas with a primary key, immutable rows, insert, select, update and delete with AND-ed WHERE conditions, rows ordered by key, sorted secondary indexes for equality and ranges, a rule-based planner with explain(), residual filters, transactions with an undo log, a read-write lock for isolation and the follow-ups, with full Java 17 code.
- 19 Version control and undo/redoUndo, redo and version history designed and coded in layers: edits as Commands on an undo and a redo stack, Mementos as immutable snapshots, a tiny git with commits that point to parents, branches, checkout, log and merge base, branch tips moved by compare-and-set, and the calculator whose last five operations can be edited, with the follow-ups and full Java 17 code.
- 20 Notification serviceA multi-channel notification service designed and coded: email, SMS and push senders as strategies, templates rendered per channel, user preferences where security alerts cannot be muted, per-category rate limits, idempotency keys, an outbox with exponential-backoff retries and a dead-letter list, delivery events observed by an engagement tracker, thread safety and the follow-ups, with full Java 17 code.
Bookings, payments and lookups
Seat holds, matching, payment states and the data structures behind them
- 21 Movie ticket bookingThe BookMyShow-style machine coding question, solved end to end: movies, screens, shows and seats, holding seats for ten minutes, all-or-nothing seat selection, a lock per show so no seat is sold twice, paying outside the lock, expiring holds, pricing as a strategy, and a full Java 17 solution with a 20-thread race.
- 22 Cab booking (ride hailing)The ride-hailing machine coding question, solved end to end: riders, drivers and trips, a trip state machine, matching the nearest free driver as a strategy, claiming a driver with compare-and-set so two riders never share one, metered fares with surge, ratings, push updates as observers, and a full Java 17 solution with a 12-rider race.
- 23 Payment gatewayThe payments machine coding question, solved end to end: a payment as a strict state machine, idempotency keys so a retry storm charges once, routing to processors with failover on timeouts but never on declines, refunds that can never exceed the charge, a ledger, webhooks as observers, and a full Java 17 solution.
- 24 Parcel locker (Amazon Locker)The parcel locker machine coding question, solved end to end: lockers, slots and parcels, best-fit slot choice as a strategy, claiming a slot with compare-and-set so two couriers never share one, one-time pickup codes, expiry and returns, notifications, and a full Java 17 solution with a 10-courier race.
- 25 HashMap from scratchThe build-your-own-HashMap machine coding question, solved end to end: buckets and chaining, why capacity is a power of two, spreading the hash, put, get and remove, the equals and hashCode contract, resizing at a load factor, bad hash codes, and a thread-safe version with lock striping, with a full Java 17 solution.
Games and devices
Boards, turns, rules and controllers: state machines you can run in a console
- 26 Tic-tac-toeA classic warm-up machine coding round, done properly: an N x N board, a win check in O(1) per move using row, column and diagonal counters, players as Strategies (a scripted human and a win-or-block bot), a read-only board view, game status, undo with a move stack, an Observer for moves, strict turns for online play and the follow-ups, with a full Java 17 solution.
- 27 ChessThe hardest board game round, designed and coded: a board with en passant and castling state, pieces as a class hierarchy with shared sliding and stepping logic, moves as Commands that undo themselves, legal moves by make and unmake, check, checkmate and stalemate, castling, en passant and promotion, perft tests that prove the move generator, and the follow-ups, with a full Java 17 solution.
- 28 Traffic signal controllerA traffic signal controller designed and coded: an intersection with two crossing roads, phases as States (green, yellow, all red, walk, emergency green, flashing red), timing in one record, a simulated clock instead of sleeps, walk buttons, emergency vehicle override, a conflict monitor that makes two crossing greens impossible, signals as observers, and the follow-ups, with a full Java 17 solution.
- 29 ATMAn ATM designed and coded end to end: requirements, cards, accounts and the bank, PIN checks with a salted hash and a three-strike lockout, the State pattern for a session, note dispensing as a Chain of Responsibility with greedy planning, withdraw with reversal on a jam, deposits, a transaction log, a race-free balance and the follow-ups, with a full Java 17 solution.
Marketplaces and money
Carts, bids, balances and bookings where every rule has an edge case
- 30 Shopping cart and checkoutA shopping cart and checkout designed and coded: requirements, catalog, cart and lines, a pricing pipeline of steps, coupons as Strategies with stacking rules, tax and shipping in exact cents, stock holds that expire on a fake clock, the payment hand-off with order states moved by compare-and-set, idempotent checkout, the last-units race and the follow-ups, with a full Java 17 solution.
- 31 Online auctionAn online auction designed and coded: requirements, auctions with start and end times, bids as an immutable chain, validation with a minimum increment and a hidden reserve price, one compare-and-set on an immutable snapshot so racing bids and closing never clash, Observer notifications for outbid bidders, closing on a fake clock, proxy bidding as an extension, and a full Java 17 solution.
- 32 Digital walletThe wallet machine coding question, solved end to end: users and wallets, adding money, peer-to-peer transfers on a double-entry ledger, a cached balance that always matches the entries, idempotency keys, lock ordering so two opposite transfers never deadlock, KYC limits as a strategy, refunds as new transactions, history, and a full Java 17 solution.
- 33 Hotel bookingThe hotel booking machine coding question, solved end to end: hotels, room types and rooms, date-range search with half-open stays, holds that expire on a fake clock, a lock per room so the last room is never sold twice, booking states, pricing by season and weekend as stacked strategies, cancellation and refund policies, and a full Java 17 solution.
Content and tools
Community sites and office tools: voting, reputation, formulas and dependencies
- 34 Q&A site (Stack Overflow)A question and answer site designed and coded: users, questions, answers, comments and tags, one vote per user per post with change and undo, reputation rules as a Strategy, privileges unlocked by reputation, one accepted answer, search by tag, Observer notifications, racing votes kept exact with an atomic ledger, and the follow-ups, with full Java 17 code.
- 35 Spreadsheet with formulasA spreadsheet engine designed and coded: cells holding numbers, text or formulas like =A1+B2*2 and =SUM(A1:A3), a recursive descent parser that builds expression trees (Interpreter), a two-way dependency graph, recalculating only affected cells in topological order, cycle detection with a clear path, error values, undo and redo with Command, and the follow-ups, with full Java 17 code.
Games and sports
Cards, pieces and live scores: rules engines and state that must never go wrong
- 36 Blackjack card gameA card game round with real money rules: cards, a multi-deck shoe with a seeded shuffle, hand values with soft and hard aces, hit, stand, double and split, dealer rules with a soft 17 switch, a round state machine, a wallet and 3 to 2 payouts, players as Strategies (scripted human and bot), observers, thread safety and the follow-ups, with a full Java 17 solution.
- 37 Jigsaw puzzleA modelling and algorithm round in one: pieces with four edges (flat, tab, blank) and shapes that must match, rotation as a property of a placement, a board that checks every fit, an edge index that finds the matching piece in O(1) instead of trying them all, a solver that builds the border then fills row by row, hints, multiplayer safety and the follow-ups, with a full Java 17 solution.
- 38 Live cricket scoreboard (Cricinfo)A live cricket scoreboard designed and coded: match, teams, innings, overs and ball events, extras that are not legal balls, wickets and dismissal types, strike rotation, batting and bowling scorecards rebuilt from a ball-by-ball log (event sourcing), formats as a Strategy, Observer feeds, undo of a wrong ball, one writer and many readers, with full Java 17 code.
Platforms, travel and trading
Bigger object models: social graphs, restaurants, flights and order books
- 39 Social network (Facebook, LinkedIn)A social network designed and coded: profiles, friend requests and follows, posts with public, friends and only me privacy, likes and comments, a news feed built by a k-way merge of recent posts, notifications as observers, blocking, name search, mutual friends and first, second and third degree connections with BFS, and races on likes and friend lists, with full Java 17 code.
- 40 Restaurant managementThe restaurant machine coding question, solved end to end: tables with time-slot reservations, a walk-in waitlist, two hosts racing for one table, orders with modifiers fired to grill and bar stations as commands, a kitchen ticket state machine, stock deducted all or nothing with low-stock observers, bill splitting strategies with tips, staff permissions and a full Java 17 solution.
- 41 Airline reservation systemThe airline reservation machine coding question, solved end to end: flight schedules versus dated flight instances, seat maps with business and economy cabins, search by route and date, seat holds that expire on a fake clock, PNR generation, demand-based fare strategies, overbooking as a policy, refund rules per fare type, check-in with boarding passes, one lock per departure, and a full Java 17 solution.
- 42 Stock brokerage with order bookThe trading app machine coding question, solved end to end: accounts with free and blocked cash and shares, market and limit orders, pre-trade checks, an order book with price-time priority, a matching engine with partial fills, order states and cancel, settlement, portfolio and P&L, Observer for trades and watchlists, one matching thread per symbol, stop-loss as an extension, and a full Java 17 solution.
Before you start
Most problems lean on a handful of patterns. Learn them once and every problem gets easier.