Cross-Problem Synthesis Problems 1–21

This section spans all twenty-one problems in this document. The same handful of lessons recur throughout — the value of working through this many problems isn't twenty-one independent tricks, it's watching a small set of ideas (check-then-act races, idempotent retries, template-vs-snapshot splits, and a short list of patterns) show up again and again in different clothing.

Pattern → Problem Map

PatternAppears InConsistent Role It Plays
StrategyParking Lot (allocation, pricing), Rate Limiter (algorithm), Splitwise (split computation), Ride-Sharing (matching, fare), Notification System (channel, rate-limit reuse), Coffee Machine (payment), Pub-Sub (overflow policy), Elevator (dispatch), Tic-Tac-Toe (winning check, AI move), ATM (transaction type), Library (fine calculation), Hotel (pricing), Movie Ticket Booking (seat pricing), Food Delivery (delivery-partner assignment), E-commerce (pricing pipeline), Stock Brokerage (order execution)Isolates an algorithm that the interviewer is expected to change mid-round — the single most reliable "extend this" test across every problem in this document, appearing in some form in 15 of the 21
Factory / Factory MethodRate Limiter (algorithm selection), Splitwise (strategy resolution), Notification System (channel resolution), Library (catalog item subtype)Resolves an enum/config value to the right Strategy instance or subtype, keeping the caller free of a growing if/else chain
FacadeEvery multi-class problem's top-level service (ParkingLot, RateLimiter, SplitwiseService, RideService, LoggerFactory, NotificationService, CoffeeMachine, FileSystem, PubSubBroker, Dispatcher, GameEngine, ChessGame, ATM, Library, Hotel, BookingService, OrderService, CheckoutService, ChatService, Broker)The single orchestration entry point callers use, hiding internal collaborators — the one pattern present in essentially all twenty-one problems
DecoratorRide-Sharing (surge over fare), E-commerce (stackable cart add-ons)The right choice specifically when a behavior is a composable modifier — stackable, order-independent-ish, layered over a base — not a mutually exclusive alternative to it; E-commerce (Problem 19) makes the Decorator-vs-Strategy boundary fully explicit for the first time in this document
State (or state-like guarded transitions)Ride-Sharing (ride lifecycle), Coffee Machine (Idle/Selecting/Dispensing/OutOfStock), Elevator (Idle/Moving/DoorsOpen/OutOfService), ATM (Idle/CardInserted/Authenticated/Dispensing), Movie Ticket Booking (ShowSeat: Available/Locked/Booked), Food Delivery (OrderState), E-commerce (OrderState)Used when illegal transitions are a real correctness risk, not just cosmetic status tracking — the density of State usage climbs sharply in the second half of this document as the problems lean more device/order-lifecycle-shaped
ObserverRide-Sharing (ride-status notifications), Notification System (event triggers), Coffee Machine (optional low-inventory alerts), Pub-Sub (the entire product), Library (hold-queue availability), Hotel (booking confirmation), Movie Ticket Booking (waitlist), Food Delivery (status push), Chat Application (the conversation itself, as both Mediator and Observer subject), Stock Brokerage (price-feed subscription driving pending limit orders)Decouples "something happened" from "who needs to know" — starts as an optional hook in Problems 5/7/8, becomes the foundational structure Problem 10 generalizes to, gets reused as a small instance five more times in Problems 15–18, converges as the structural core of Problem 20, and reappears once more in Problem 21 as the mechanism that avoids polling a price feed
Singleton — justified once, rejected everywhere else it's temptingJustified: Logging Framework's LoggerFactory/registry. Explicitly rejected: Parking Lot (ParkingLot), Ride-Sharing (RideService), Elevator (Dispatcher), Stock Brokerage (Broker)The contrast is the lesson — Singleton is correct exactly when there is genuinely one process-wide coordination point with no meaningful alternative construction (a logger registry); it's a naive shortcut everywhere it's used to avoid passing a dependency, and it shows up as a tempting-but-wrong choice for coordinator/dispatcher classes specifically, four separate times in this document
Chain of ResponsibilityLogging Framework (log-level threshold checks), ATM (denomination-handler cash dispensing)Fits naturally when a request should be handled — or passed along — by a sequence of independent handlers, each with veto or partial-handling power
CompositeFile System (File/Directory hierarchy)Unifies leaf and container nodes under one interface so client code never needs to branch on which it has
VisitorFile System (DiskUsageVisitor, SearchVisitor)Keeps an ever-growing set of read-only aggregate operations out of the base node interface — a direct ISP payoff, added as new classes rather than new methods
IteratorFile System (directory traversal)Separates "how to walk the structure" from "what to do at each node," letting the same traversal support multiple aggregate operations without duplicating walk logic
Template Method — rejected once, used once, then made explicitly conditional a third timeRejected: Coffee Machine's per-beverage brewing. Present: Notification System's shared send-pipeline. Explicitly conditional/deferred: Tic-Tac-Toe's TurnBasedGame — build only once a second game genuinely needs the shared skeletonThe distinguishing question is always the same: do subclasses genuinely need to override specific steps of a fixed algorithm (Notification System, yes), or is the "variation" actually just data (Coffee Machine's Recipe, no) — and is a second concrete case even in scope yet (Tic-Tac-Toe, not unless asked)
BuilderHotel Reservation System (ReservationRequestBuilder for a request with several optional parts)Fits when construction has multiple optional, independently-meaningful parts that don't all apply every time — the alternative is a telescoping constructor or validating partial state ad hoc throughout the object's life
CommandChess Game (Move with execute()/undo(), backed by a MoveHistory stack)Fits when an action needs to be represented as a first-class object specifically because it must be queued, logged, or reversed later — undo/redo is the canonical justification, and Chess is the one problem in this document that genuinely needs it
MediatorChat Application (GroupConversation decoupling participants from direct references to each other)Fits specifically when a growing number of peer objects would otherwise need direct references to each other (an O(n²) mesh) — Chat's Conversation plays this role simultaneously with its Observer role, which is the clearest illustration in this document that these two patterns solve different problems and can coexist on the same class
Explicitly-considered-and-rejected patterns as a design-maturity signalSplitwise (Payment as sibling, not subclass, of Expense), Ride-Sharing (Decorator, not a second Strategy, for surge), Notification System (Bridge for category×channel), Coffee Machine (Template Method for brewing), Pub-Sub (Bridge for delivery-model × persistence), Elevator (Singleton for Dispatcher), Chess (Strategy for piece movement — type and movement rule always change together), E-commerce (Strategy for add-ons / Decorator for pricing pipeline — the roles, not just the patterns, would be swapped), Stock Brokerage (Singleton for Broker)Naming a plausible-looking pattern and explaining precisely why it doesn't fit is a stronger signal than reaching for any pattern reflexively — this shows up explicitly in nine of the twenty-one problems in this document, spanning every major pattern family

Cross-Problem Comparison

ProblemPrimary ConceptMain Design ChallengeImportant PatternConcurrencyDifficulty
Parking LotResource allocationAtomic check-and-occupy on a shared spotStrategy (allocation + pricing)Check-then-act race on spot stateBeginner → Intermediate
LRU CacheO(1) cache evictionRecognizing "get is a write" for LRU orderingWhole-class Strategy (not field-level) for eviction policyLock contention on every read; sharding as the scale answerIntermediate
Rate LimiterTraffic control algorithmsTimestamp-as-parameter for testability; distributed atomicityStrategy + Factory over algorithmsPer-client fine-grained locks; Redis Lua-script atomicity distributedIntermediate → Advanced
SplitwiseLedger correctnessSum-to-zero invariant under concurrent writes; debt simplificationStrategy (splits); Payment as sibling, not subclass, of ExpenseMulti-pair consistent lock ordering; idempotent settle-upIntermediate → Advanced
Ride-SharingReal-time matching + lifecycleAtomic driver reservation; two independent strategies (match, fare); LLD/HLD boundaryStrategy + Decorator + State + Observer, all in one problemDouble-booking race on driver status; high-frequency location writesAdvanced
Logging FrameworkConfigurable, extensible logging pipelineThreshold filtering and multi-destination fan-out without a growing if/else chainChain of Responsibility (level filtering); Singleton (justified, contrast with Problems 1/5/11)Async appender queue with an explicit overflow policy; thread-safe registry accessIntermediate (Pattern Showcase)
Notification SystemMulti-channel event notificationPer-channel send pipeline plus dedupe/rate-limiting, reusing Problem 3's RateLimiter directlyTemplate Method (send pipeline); Factory (channel resolution); Bridge explicitly rejectedIdempotent dedupe under retries; rate-limiter reuse's existing concurrency guaranteesIntermediate → Advanced
Coffee Vending MachinePhysical-device state machineAtomic, all-or-nothing ingredient reservation with rollback; Template Method explicitly rejectedState (headline); Strategy (payment)Shared-hopper check-then-act race across brewing slots — smallest-scale instance of the recurring raceBeginner → Intermediate
File SystemHierarchical resource treeUniform file/directory treatment; keeping aggregate queries off the base node interface; deadlock-free cross-directory moveComposite (headline); Visitor; IteratorReaders-writer lock per node; canonical-path lock ordering for move()Intermediate → Advanced
Pub-Sub / Message QueueAsynchronous fan-out messagingBackpressure under a slow subscriber; idempotent consumers under at-least-once delivery; per-partition-only orderingObserver (foundational, generalizing Problems 5/7/8); Strategy (overflow policy)Bounded per-subscriber queues; retry/dead-letter handling; ordering-scope trade-off is centralAdvanced + Concurrency
Elevator SystemReal-time dispatch + device lifecycleAtomic select-then-claim hall-call assignment; SCAN-style per-car schedulingState (car lifecycle); Strategy (dispatch); Singleton explicitly rejected for DispatcherDouble-assignment race on hall-call selection, same shape as Ride-Sharing's driver raceIntermediate → Advanced+Concurrency
Tic-Tac-Toe / Board Game EngineGeneric rule-checking over a gridA direction-scan win-check that generalizes to K-in-a-row, not hardcoded win-lines; Player polymorphism over a boolean flagStrategy (winning check, AI move); Template Method explicitly deferred pending a second gameNone load-bearing — the pattern-boundary lessons are the point of this problemBeginner → Intermediate (Pattern Showcase)
Chess GameRule-bound simulate-then-commit movesMove as a first-class, reversible Command; check detection reusing getValidMoves() rather than a duplicate algorithmCommand (headline, undo/redo via MoveHistory); Strategy explicitly rejected for piece movementNot the focus — single-player-turn correctness (simulate → validate → commit) is the design challenge insteadIntermediate → Advanced
ATM MachineCross-channel financial state machineDebit-before-dispense ordering with compensating credit on failure; greedy denomination dispensingState (headline, ATM lifecycle); Chain of Responsibility (denomination handlers); Strategy (transaction type)Cross-channel check-then-act balance race, same shape as Parking Lot/SplitwiseIntermediate
Library Management SystemCatalog metadata vs. per-copy lifecycleBook/BookItem split; FIFO hold queue with availability notificationObserver (hold queue, small instance); Strategy (fines); Factory Method (catalog item type)Check-then-act race on the last available copy of a titleIntermediate
Hotel Reservation SystemDate-range availabilityAvailability as an interval structure, not a boolean flag; multi-part reservation request constructionBuilder (headline, reservation request); Strategy (pricing); Observer (booking notifications)Check-then-act race on overlapping date-range bookings; DB exclusion-constraint alternative discussedIntermediate → Advanced+Concurrency
Movie Ticket Booking SystemHigh-contention seat inventorySeat/ShowSeat split under real contention; TTL soft lock → payment-gated hard commit; multi-seat deadlock avoidanceState (headline, ShowSeat lifecycle); Strategy (pricing); Observer (waitlist)The concurrency showcase of the document: canonical lock ordering for multi-seat holds; idempotent payment confirmationAdvanced (Concurrency Showcase)
Restaurant / Food Delivery SystemOrder lifecycle + delivery dispatchMenuItem/OrderLineItem price-snapshot split; atomic select-then-claim delivery-partner assignmentState (headline, order lifecycle); Strategy (assignment); Observer (status push, reusing Pub-Sub)Select-then-claim race on delivery partners (Elevator's dispatcher race, reapplied); out-of-order/duplicate status eventsIntermediate → Advanced
E-commerce Shopping Cart & CheckoutComposable pricing + inventory correctnessDecorator (add-ons) vs. Strategy (pricing pipeline) boundary, made fully explicit; Cart/Order mutable-vs-frozen splitDecorator (headline, add-ons); Strategy (pricing pipeline); State (order lifecycle)Check-then-act inventory decrement race; multi-item checkout deadlock avoidance; idempotent payment webhookIntermediate → Advanced
Chat Application (WhatsApp-style)Real-time multi-party messagingConversation as both Mediator (decouples participants) and Observer subject (delivery fan-out) — the capstone of the document's Observer arcMediator (group chat); Observer (headline, closing the arc from Problems 5/7/10/15–18); State (per-recipient message receipts)Server-assigned per-conversation ordering; idempotent cursor-based reconnect replay; multi-device presence raceAdvanced
Stock Brokerage SystemFinancial account correctness under concurrencyReserve-then-settle funds/holdings so concurrent orders on one account can't double-spend or oversell; feed-execution vs. real order-matching scope boundaryStrategy (market/limit execution); Observer (price-feed subscription); Facade (Broker)Atomic reserve per account; cancel-vs-execute race on order status; per-account lock granularity gives free parallelism across usersAdvanced (Concurrency & Consistency)

Recurring Interview Signals Across All Twenty-One