LLD Interview Problems — Cheat Sheet
Low Level Design · 15 topics. Download the PDF or the Instagram carousel and share it.
Design a Parking Lot
Model a multi-floor parking lot that assigns spots based on vehicle size and calculates fees using a pluggable pricing strategy.
- ✓Use enums for SpotType and VehicleType to avoid stringly-typed comparisons and enable exhaustive switch expressions.
- ✓Singleton ParkingLot with Double-Checked Locking + volatile ensures one global instance under concurrent access.
- ✓Strategy pattern for pricing isolates fee logic — adding a WeekendSurgePricing requires zero changes to ParkingLot.
- ✓Factory method (or a static VehicleFactory) decouples callers from concrete Car/Truck/Motorcycle constructors.
// No code here — just requirements // Entities: ParkingLot, ParkingFloor, ParkingSpot, Vehicle, ParkingTicket, PaymentService // Patterns : Singleton (ParkingLot), Factory (vehicle/spot), Strategy (pricing)
Design an Elevator System
Model a multi-elevator system with a controller that schedules requests using the LOOK algorithm and tracks each elevator as a state machine.
- ✓State pattern encapsulates per-state behaviour: MovingUpState silently drops downward requests, IdleState accepts any.
- ✓LOOK algorithm outperforms FCFS by batching same-direction requests, cutting average wait time significantly.
- ✓Observer (DoorSensorListener) decouples door-open events from safety systems, display screens, and logging.
- ✓Using a TreeSet for destinations gives O(log n) add and O(1) min/max access, perfect for LOOK direction checks.
// Entities : ElevatorSystem, Elevator, ElevatorController, Request, Direction, ElevatorState // Patterns : State (elevator lifecycle), Strategy (LOOK scheduler), Observer (door sensors)
Design a Library Management System
Model a library that manages physical book copies, member loans, reservations, and automated overdue fine calculation.
- ✓Separate Book (metadata) from BookItem (physical copy) — one ISBN maps to many barcodes, each with independent status.
- ✓Strategy for fine calculation means adding a weekend-surcharge rule is a new class, not a modification of Library.
- ✓Observer decouples overdue detection from notification channels — email, SMS, and push can all be separate observers.
- ✓Member.canBorrow() encapsulates the borrow-limit rule so Library never hard-codes member type logic.
// Entities : Library, Book, BookItem, Member, LibraryCard, Loan, Fine, Catalog, Reservation // Patterns : Observer (overdue alerts), Strategy (fine calc), Factory (member types)
Design an Online Bookstore
Model an e-commerce bookstore with a cart, pluggable discount strategies, stackable promotions via Decorator, and inventory-alert observers.
- ✓Decorator stacks discounts at runtime: new FlatDiscountDecorator(new PercentageDiscount(10), 50) chains two promotions without modifying either class.
- ✓Strategy for shipping means swapping Free-over-threshold for Prime-style free shipping is a one-liner constructor change.
- ✓Observer on Inventory keeps the order flow clean — restocking alerts are entirely separate from checkout logic.
- ✓Using record for CartItem gives free equals/hashCode/toString, simplifying duplicate-item detection in the cart.
// Entities : BookStore, Book, Cart, CartItem, Order, OrderItem, Inventory, Discount, ShippingStrategy // Patterns : Strategy (discount + shipping), Decorator (stackable discounts), Observer (inventory alerts)
Design an ATM Machine
Model an ATM as a state machine with pluggable transaction commands and a validation chain, communicating with a remote BankServer.
- ✓State pattern eliminates nested if-else on ATM status — each state class only implements what is legal in that state.
- ✓Command pattern makes transactions first-class objects: they can be logged, queued, retried, or audited independently.
- ✓Chain of Responsibility for validation keeps each check (PIN, balance, daily limit) single-responsibility and reorderable.
- ✓BankServer as an interface decouples the ATM from any specific bank backend, enabling unit testing with a stub.
// Entities : ATM, Card, Account, BankServer, Transaction types, ATMState subtypes // Patterns : State (ATM lifecycle), Command (transactions), Chain of Responsibility (validation)
Design a Chess Game
Model a two-player chess game with an abstract Piece hierarchy using Template Method for move validation, Command for undo/redo, and a Board composite.
- ✓Template Method in Piece.isValidMove() prevents code duplication: out-of-bounds and friendly-fire checks live once in the base class.
- ✓Declaring canMove() abstract forces every new piece subclass to define its own movement — no switch/instanceof needed.
- ✓Command (Move record) stores enough data for undo: restore from/to squares and re-place the captured piece.
- ✓Composite view of Board: GameController only calls board.getSquare() — it never traverses the 2D array directly.
// Entities : Board, Square, Piece hierarchy, Player, Move, GameController, GameStatus // Patterns : Template Method (Piece.isValidMove), Command (Move undo/redo), Composite (Board of Squares)
Design Snake and Ladder Game
Model a configurable Snake and Ladder board game with multiple players, pluggable dice strategies, and observer-based game-event notifications.
- ✓Strategy pattern for dice means swapping StandardDice for FixedDice in unit tests requires zero changes to GameController.
- ✓Storing snakes and ladders as Map<Integer, Integer> gives O(1) teleport resolution; no iteration over the board is needed.
- ✓Observer decouples event reactions (logging, UI updates, sound effects) from the core game loop entirely.
- ✓Capping movement at exactly board size (not wrapping) is a rules-correctness detail interviewers specifically probe.
// Entities : Game, Board, Player, Dice, Snake, Ladder, Cell, GameController // Patterns : Strategy (dice rolling), Observer (game events), Factory (board setup)
Design a Hotel Management System
Model a hotel that manages room types, bookings, guest check-in/check-out, and invoice generation using Strategy and Observer patterns.
- ✓RoomStatus transitions (AVAILABLE→BOOKED→OCCUPIED→AVAILABLE) must be atomic under concurrent booking requests.
- ✓Strategy for pricing means switching from flat to seasonal rates requires only changing the injected PricingStrategy — zero changes to Hotel or Booking.
- ✓Observer for housekeeping decouples checkout from cleaning workflows — new notification channels (SMS, app) are new observer implementations.
- ✓Separating Book (metadata) from Room (physical asset with status) mirrors the Library BookItem pattern and prevents status confusion.
// Entities : Hotel, Room, RoomStatus, RoomType, Guest, Booking, Invoice, HousekeepingTask // Patterns : Strategy (pricing), Observer (housekeeping), Factory (room creation)
Design a Movie Ticket Booking System
Model a cinema booking system with shows, seat types, concurrent seat locking, and a Singleton BookingSystem entry point.
- ✓Synchronized seat.lock() prevents two threads from booking the same seat — rollback releases all acquired locks on partial failure.
- ✓Singleton BookingSystem ensures a single coordination point across all concurrent booking requests.
- ✓Strategy for seat pricing makes recliner pricing configurable without touching Booking or Show.
- ✓Observer fires confirmation events after payment so email/push services are fully decoupled from the booking transaction.
// Entities : BookingSystem, Movie, Theatre, Screen, Show, Seat, Booking, Payment // Patterns : Singleton (BookingSystem), Strategy (seat pricing), Observer (booking confirmation)
Design a Ride-Sharing App like Uber
Model a ride-sharing platform with driver matching, trip state machine, surge pricing strategy, and real-time status observer notifications.
- ✓TripStatus transitions must be validated — COMPLETED cannot go back to IN_PROGRESS; enforce this with explicit transition guards.
- ✓Strategy for pricing allows surge multiplier to be updated at runtime based on demand signals without restarting the app.
- ✓MatchingService is isolated from Trip — changing matching algorithm (nearest vs best-rated) requires only a new MatchingService implementation.
- ✓Observer on Trip decouples real-time notifications from the core ride lifecycle, enabling push, SMS, and audit logging simultaneously.
// Entities : RideSharingApp, Driver, Rider, Trip, TripStatus, Location, MatchingService // Patterns : Strategy (pricing), Observer (status updates), State (trip lifecycle), Command (trip actions)
Design a Food Delivery App like Swiggy
Model a food delivery platform with restaurant ordering, order status machine, delivery agent assignment, and ETA calculation using Strategy and Observer.
- ✓OrderStatus state machine prevents illegal transitions — a CANCELLED order cannot move to DELIVERED; enforce with explicit allowed-transition sets.
- ✓DeliveryAssignmentStrategy decouples agent selection logic — swapping NearestAgent for HighestRatedAgent requires zero changes to Order.
- ✓Observer on Order keeps the customer notification layer completely separate from order processing, enabling multi-channel delivery.
- ✓Chain of Responsibility for the order processing pipeline makes adding a fraud-check step a new handler with zero modification to existing handlers.
// Entities : FoodDeliveryApp, Restaurant, Menu, MenuItem, Order, OrderItem, OrderStatus, DeliveryAgent // Patterns : Observer (status), Strategy (assignment + ETA), Chain of Responsibility (order pipeline)
Design a Notification System
Build a multi-channel notification system with pluggable channel handlers, template support, retry logic via Chain of Responsibility, and event-driven dispatch.
- ✓ChannelHandler as an interface makes adding WhatsApp or Slack a new class with zero changes to NotificationService.
- ✓RetryChannelHandler is a Decorator that wraps any handler transparently — retry logic is not duplicated across channel implementations.
- ✓Template-based messaging decouples notification content from delivery infrastructure, enabling marketing to update copy without code changes.
- ✓Observer-driven triggering (ApplicationEvent → NotificationService) ensures business code never directly instantiates notification requests.
// Entities : NotificationService, NotificationRequest, NotificationChannel, ChannelHandler, NotificationTemplate // Patterns : Strategy (channel selection), Chain of Responsibility (retry/fallback), Observer (event-driven trigger)
Design a Rate Limiter
Implement multiple rate-limiting algorithms — Token Bucket, Sliding Window, Fixed Window — behind a common interface with thread-safe implementations.
- ✓Token Bucket allows controlled bursting — tokens accumulate up to max capacity, smoothing bursty traffic better than Fixed Window.
- ✓Sliding Window Log is the most accurate algorithm but stores O(requests) timestamps per key — use Fixed Window for memory efficiency at scale.
- ✓Fixed Window suffers the boundary burst problem: a user can make 2× the limit in two seconds straddling a window boundary.
- ✓synchronized on tryAcquire() is simple but limits throughput; production systems use Redis atomic scripts (EVAL) for distributed rate limiting.
// Algorithms : TokenBucket, SlidingWindow, FixedWindow, LeakyBucket // Patterns : Strategy (algorithm selection), Decorator (chaining limiters)
Design an LRU Cache
Implement an O(1) get/put LRU Cache using a doubly linked list and HashMap, with an optional thread-safe variant using ReadWriteLock.
- ✓O(1) get and put requires both a HashMap (lookup) and a DoublyLinkedList (order); neither alone achieves both operations in O(1).
- ✓Sentinel head and tail nodes eliminate null checks at list boundaries, simplifying add/remove logic.
- ✓ReadWriteLock allows concurrent reads but exclusive writes — ideal when cache reads vastly outnumber writes.
- ✓Java LinkedHashMap(capacity, 0.75f, true) with removeEldestEntry() is the production shortcut but interviewers test the manual DLL implementation.
// Data structures : HashMap<K, DLLNode> + DoublyLinkedList // Patterns : Composite (node + map together), Decorator (stats tracking layer)
Design a Pub-Sub System
Build an in-process publish-subscribe system with topics, async delivery via ExecutorService, subscription management, and configurable delivery guarantees.
- ✓CopyOnWriteArrayList for subscribers allows safe iteration during publish while cancel() modifies the list concurrently.
- ✓ExecutorService for async delivery isolates subscriber failures — a slow subscriber does not block the publisher or other subscribers.
- ✓Subscription.cancel() removes the subscriber from the topic atomically; volatile active flag prevents delivery after cancellation.
- ✓AT_LEAST_ONCE delivery requires retry on subscriber failure; EXACTLY_ONCE requires distributed coordination (idempotency keys, transactions).
// Entities : PubSubSystem, Topic, Message, Publisher, Subscriber, Subscription, EventBus // Patterns : Observer (pub-sub), Command (messages), Strategy (delivery guarantee)