Sweaty Imposter

OOP Design

16 classic interview prompts, each with the canonical class breakdown.

Design an object-oriented parking lot with multiple levels, multiple spot sizes (motorcycle, compact, large), and dynamic pricing. A ticket is issued on entry and used to compute the bill on exit.

Classes to Define
ParkingLot: Top-level aggregate that owns Levels, accepts park/unpark requests, and delegates spot assignment.
Level: Owns a collection of ParkingSpots and tracks availability counters per size for O(1) lookup.
ParkingSpot: A single physical spot with a size and current occupant; knows whether a given vehicle fits.
Vehicle (abstract) / Motorcycle, Car, Truck: Encodes size and license plate; subclasses exist mainly so spot-fit logic stays polymorphic.
Full Breakdown and Java Sketch

Design a library system that tracks books, members, check-outs, holds, and fines. A single title may have many physical copies; members can place holds when all copies are checked out.

Classes to Define
Book: Logical title-level record (ISBN, author, subject); does not represent a physical item.
BookCopy: A physical, checkoutable instance of a Book with a barcode, location, and current status.
Member: Library patron with status, current loans, holds, and outstanding fines.
Loan: Open transaction linking a BookCopy to a Member with checkout date and due date.
Full Breakdown and Java Sketch

Design an elevator control system for a building with N elevators and F floors. Riders press hall buttons on each floor (up/down) and car buttons inside each elevator. The system must dispatch efficiently and serve every request.

Classes to Define
Building: Owns the set of Elevators and Floors and routes hall calls into the Dispatcher.
Elevator: Single car with current floor, direction, capacity, and an ordered set of pending stops.
Floor: Hall call buttons (up/down) and the up/down indicators; emits HallRequest events.
Request (HallRequest, CarRequest): Value object representing a single ask; distinguishing hall vs car matters for scheduling.
Full Breakdown and Java Sketch

Design a vending machine that holds inventory across slots, accepts coins and bills, dispenses a product, and returns correct change. Model the full transaction lifecycle including cancellation.

Classes to Define
VendingMachine: Top-level facade exposing insert, select, cancel, and dispense; owns the current transaction state.
Inventory: Maps slot codes to (Product, count); enforces decrement-on-dispense and supports restock.
Product: Immutable product descriptor: name, price, slot affinity.
CashRegister: Tracks denomination counts; computes whether a given change amount is makeable and produces the payout.
Full Breakdown and Java Sketch

Design an ATM that authenticates a cardholder, then supports balance inquiry, withdrawal, deposit, and transfer. Enforce per-account daily withdrawal limits and machine cash limits.

Classes to Define
ATM: Hardware-facing facade coordinating card reader, keypad, cash dispenser, and deposit slot.
Session: Authenticated user session bound to a Card; expires on logout, timeout, or completion.
Card: Holds card number and links to one or more Accounts; carries per-card daily limits.
Account: Bank account with balance and daily-withdrawal accumulator; mutated only via Transactions.
Full Breakdown and Java Sketch

Design a chess game: model the board, pieces, legal-move generation, turn order, and game-end detection (checkmate, stalemate, draws). Focus on a piece hierarchy that's easy to extend.

Classes to Define
Game: Owns Board, two Players, move history, and game state; the entry point for makeMove.
Board: 8x8 grid of Squares; provides piece lookup, move application, and snapshotting for undo.
Square: A coordinate that may hold a Piece; thin wrapper that simplifies move generation.
Piece (abstract): King, Queen, Rook, Bishop, Knight, Pawn: Each subclass generates its candidate moves from a position; legality is filtered by Board.
Full Breakdown and Java Sketch

Design an Amazon-style online bookstore: catalog, search, cart, checkout, orders, and payment. Focus on the domain model and how state moves through the order lifecycle.

Classes to Define
Catalog: Searchable index of Books with price and availability lookups; abstracts the search backend.
Book: Product entity: ISBN, title, author, price, and stock pointer.
User: Account identity holding addresses, payment methods, and order history references.
Cart: Per-user mutable collection of CartItems; computes subtotal and survives across sessions.
Full Breakdown and Java Sketch

Design a hotel reservation system that supports searching available rooms by date range and room type, booking with pricing, modifying or cancelling reservations, and check-in/check-out at the property.

Classes to Define
Hotel: Owns Rooms and exposes search/book operations against its inventory.
Room: Physical room with type, number, and floor; holds long-lived attributes, not pricing.
RoomType: Class of room (Standard, Suite) used for search and base pricing; many Rooms per type.
Reservation: Guest's booking covering a date range and a RoomType, with a price quote and status.
Full Breakdown and Java Sketch

Design an in-process pub/sub system: publishers post messages to topics, and subscribers receive messages from topics they subscribe to. Support multiple subscribers per topic, retention, and delivery guarantees.

Classes to Define
Broker: Top-level registry of Topics and Subscriptions; the entry point for publish and subscribe.
Topic: Named channel that owns its message log and the set of Subscriptions reading from it.
Message: Immutable record with payload, headers, offset, and timestamp.
Subscription: Per-subscriber state on a Topic: handler reference, current offset, ack state.
Full Breakdown and Java Sketch

Design a movie ticket booking system: theaters with multiple screens, movies showing at scheduled times, seat selection with temporary holds during checkout, and payment that confirms the booking.

Classes to Define
Movie: Film catalog entry: title, duration, rating, language; independent of any showing.
Theater: Physical venue that owns one or more Screens and a location.
Screen: Auditorium with a fixed seat layout; hosts Shows over time.
Show: A specific Movie on a specific Screen at a specific time; owns the per-seat availability for that showing.
Full Breakdown and Java Sketch

Design the core of a Splitwise-style app: users form groups, add expenses paid by one person and split equally, by exact amounts, or by percentage, and see who owes whom. Support settling up and simplifying debts within a group.

Classes to Define
User: Identity and display name; holds no balance state of its own.
Group: Owns members and the ordered list of Expenses and Settlements; the boundary for balance computation.
Expense: Immutable record of payer, total in minor units, description, and the computed Splits.
Split: One participant's share of an Expense as an exact amount in minor units.
Full Breakdown and Java Sketch

Design an in-process rate limiter library that services call before handling a request. It must limit per key (user, API key, or IP), support several algorithms, and stay correct under concurrent access.

Classes to Define
RateLimiter: Facade that resolves the rule for a request, finds the key's limiter state, and returns a Decision.
RateLimitRule: Immutable config: limit, window or refill rate, burst size, and the algorithm to use.
RuleResolver: Maps a request context (tier, endpoint, key type) to a RateLimitRule.
LimiterAlgorithm (interface) / TokenBucket, FixedWindow, SlidingWindowLog: Encapsulates per-key state and the tryAcquire logic for one algorithm.
Full Breakdown and Java Sketch

Design an in-memory file system that supports directories and files, path-based operations (mkdir, ls, create, read, write, move, and delete), and metadata such as size and timestamps.

Classes to Define
FileSystem: Facade exposing path operations; resolves paths and delegates to the tree.
Entry (abstract): Shared base for files and directories with name, parent, and timestamps.
File: Leaf entry holding content bytes; its size is the content length.
Directory: Composite entry holding a sorted map of child names to Entries; its size sums its children.
Full Breakdown and Java Sketch

Design a multiplayer Snake and Ladder game: a board of 100 cells with snakes and ladders, two or more players taking turns rolling a die, and a winner who lands exactly on the last cell.

Classes to Define
Game: Owns the Board, the Player queue, the Dice, and the game status; runs the turn loop.
Board: Holds the size and a map from start cell to Jump; returns the final cell for any landing position.
Jump / Snake, Ladder: A start and end cell; a snake goes down and a ladder goes up, validated at construction.
Player: Name and current position.
Full Breakdown and Java Sketch

Design a logging library in the style of Log4j or Logback: named loggers, log levels, multiple destinations (console, file, and remote), configurable formats, and minimal overhead on the calling thread.

Classes to Define
LoggerFactory: Creates and caches Loggers by name and builds the parent hierarchy.
Logger: Named entry point with debug, info, warn, and error methods; checks the level before building a record.
Level (enum): Ordered severities with a numeric rank for fast comparison.
LogRecord: Immutable event: timestamp, level, logger name, thread, message, fields, and throwable.
Full Breakdown and Java Sketch

Design the object model for a notification service that sends email, SMS, and push messages. Callers send an event like 'order shipped'; the service renders a template, respects user preferences and quiet hours, retries failures, and avoids duplicate sends.

Classes to Define
NotificationService: Entry point that validates a request, deduplicates it, and runs the pipeline.
NotificationRequest: Immutable input: recipient ID, event type, payload, idempotency key, and priority.
PreferenceResolver: Applies opt-outs, quiet hours, and event defaults to choose channels.
TemplateRenderer: Renders subject and body per channel and locale from an event's template set.
Full Breakdown and Java Sketch