Low-level design, the way Google asks it.
100 object-oriented and low-level design questions reported from Google interviews, the 68 concepts they are built from, and every one of the 100 solved in the same six-step framework with a class diagram and working code.
How to read these notes
Two halves. Concepts are the building blocks of object-oriented design: each article starts from a small program written the obvious way, refactors it one step at a time with the code after every step, says why the result holds up, and what it costs. The 100 problems are the class-design, machine-coding and component-API questions candidates report from Google loops, each solved the same way: requirements and use cases, the entities and a class diagram, the interfaces, the patterns and the choices behind them, the core flow with working Python, and the extensions and concurrency follow-ups interviewers probe. Every solution links the concepts it uses, and every concept lists the problems it appears in.
Read the concepts first if system design is new to you; read a problem first if you have an interview next week and want the rhythm. The sidebar ticks what you have finished, in this browser only.
Concepts
Object-oriented foundations
Classes, objects and the four ideas everything else rests on.
- Encapsulation Hiding data behind methods so an object's rules cannot be broken from outside.
- Abstraction and interfaces Describing what an object does, not how, so callers depend on a promise.
- Inheritance versus composition Being a kind of thing, or having a thing: when each is right.
- Polymorphism One call, many behaviours: the code that removes the if-else ladder.
- Value objects and immutability Objects defined by their value, never changed, safely shared.
- Enums versus class hierarchies A fixed list of kinds, or a family of classes that behave differently.
SOLID and design principles
The rules that keep a design easy to change.
- Single responsibility One reason to change per class.
- Open-closed principle Add behaviour by adding code, not by editing what works.
- Liskov substitution A subclass must be usable wherever its parent is.
- Interface segregation Small interfaces so classes are not forced to fake methods.
- Dependency inversion and injection Depend on interfaces and receive collaborators from outside.
- Law of Demeter and tell-don't-ask Talk to your neighbours, not your neighbours' insides.
- DRY, KISS and YAGNI Remove duplication, keep it simple, build what is asked.
Creational patterns
How objects get made.
- Factory method and simple factory One place that decides which concrete class to create.
- Abstract factory A family of related objects created together.
- Builder Constructing a complex object step by step with readable code.
- Singleton and its alternatives Exactly one instance, and why dependency injection is usually better.
- Prototype and registries Cloning a configured object, or looking one up by name.
- Object pools Reusing expensive objects instead of making new ones.
Structural patterns
How objects are composed into bigger ones.
- Adapter Making an existing class fit the interface you need.
- Decorator Adding behaviour by wrapping, without subclass explosion.
- Composite Treating a tree of parts and wholes uniformly.
- Facade One simple front door to a complicated subsystem.
- Proxy A stand-in that controls access: lazy, cached, protected or remote.
- Flyweight Sharing the heavy, unchanging part of millions of small objects.
- Bridge Separating an abstraction from its implementation so both can vary.
Behavioral patterns
How objects talk and divide up work.
- Strategy Swapping an algorithm at runtime by passing an object.
- State machines and the State pattern Behaviour that depends on a mode, without a wall of conditionals.
- Observer and event listeners Telling interested objects something happened, without knowing who they are.
- Command Turning an action into an object you can queue, log and undo.
- Template method A fixed skeleton of steps with a few steps left to subclasses.
- Iterator and generators Walking a collection without exposing how it is stored.
- Chain of responsibility Passing a request along handlers until one takes it.
- Mediator One object that coordinates many, so they do not all know each other.
- Memento and undo Saving and restoring an object's state without breaking encapsulation.
- Visitor Adding operations over a class family without touching the classes.
- Specification and rule objects Business rules as composable objects you can and, or and not.
Modeling and API shape
Turning a problem statement into classes and method signatures.
- From requirements to classes Nouns, verbs and the use-case walk that finds the classes.
- Relationships and multiplicity Association, aggregation, composition, and the numbers on the lines.
- Reading and drawing class diagrams The notation interviewers expect, and what to leave out.
- Designing method signatures Inputs, outputs, errors and names that make misuse hard.
- Errors, exceptions and validation Failing loudly at the boundary and never in the middle.
- Identity, equality and hashing When two objects are the same object, and when they are equal.
- Domain events Recording what happened as objects, so other parts can react later.
- Layers and boundaries Keeping domain logic away from storage and interfaces.
State, data structures and algorithms inside objects
Choosing what to store and how to find it fast.
- Hash map plus linked list (LRU) O(1) lookup and O(1) recency with two structures that point at each other.
- Heaps and priority queues in object design Scheduling, ranking and timers with a heap behind a clean interface.
- Tries behind prefix APIs Autocomplete and dictionary objects built on a character tree.
- Modeling boards and grids Cells, moves, win checks and bounds for games and simulators.
- Time, TTLs and expiry inside objects Injecting a clock, expiring entries lazily or with a timer wheel.
- Sliding windows and counters Rate limiters and hit counters as objects with bounded memory.
- Intervals and scheduling Meetings, bookings and conflicts as interval arithmetic.
- Graphs inside objects Dependencies, routes and social links as adjacency behind an API.
- Parsing and tokenizing Expressions, commands and file paths turned into structures.
- Snapshots and versioning Keeping history cheaply: copies, diffs and persistent structures.
Concurrency in one process
Making objects safe when many threads use them.
- Locks and mutexes Making a critical section one-at-a-time, and what it costs.
- Thread-safe collections and atomics Counters and maps many threads can share.
- Producer-consumer and bounded queues Decoupling threads with a queue that blocks when full or empty.
- Read-write locks Many readers at once, one writer alone.
- Deadlock and how to avoid it Lock ordering, timeouts and why two locks are twice the danger.
- Optimistic concurrency and versions Check-then-write with a version number instead of a lock.
- Executors, futures and timers Running work on a pool and getting the result back.
- Idempotent operations Making a repeated call harmless inside a single process too.
Quality, testing and extensibility
Proving it works and keeping it changeable.
- Designing for unit tests Seams, fakes and injected clocks that make a class testable.
- Extensibility points Deciding in advance what will change, and leaving one door for it.
- Naming and readability Code the interviewer can follow without you narrating.
- Trade-offs and over-engineering When a pattern is a cost, and how to say so.
- The machine-coding rubric What a 90-minute coding-plus-design round is graded on.
The 100 problems, solved
Caches and in-memory stores
Maps, sets and caches with sharp complexity promises.
- 001 · Design an LRU cache get and put in O(1), evicting the least recently used key; the edge case is a get followed by a put.
- 002 · Design a thread-safe LFU cache Evict the least frequently used key in O(1), then make it safe for many threads without one big lock.
- 003 · Design a cache manager with pluggable eviction and TTL One cache class, eviction policy injected (LRU, LFU, FIFO), entries that expire on time.
- 004 · Design a key-value store with TTL put with a lifetime, get that never returns an expired value, and a capacity cap on top.
- 005 · Design a time-based key-value store set(key, value, t) and get(key, t) returning the latest value at or before t, with out-of-order inserts.
- 006 · Design an in-memory database with transactions Tables, indexes and begin/commit/rollback in one process.
- 007 · Design a hash map and hash set from scratch Buckets, hashing, collisions and resizing, behind the familiar interface.
- 008 · Design a map with constant-time putAll put, get and a putAll(value) that overwrites every key in O(1), interacting correctly with later puts.
- 009 · Design a set with O(1) insert, delete and getRandom An array plus an index map, with swap-with-last deletion.
- 010 · Design a phone book with concurrent access Add, lookup and prefix search over contacts, then make it safe for readers and writers.
- 011 · Design a frequency-ordered container with weighted random pick Track item counts, list by frequency, and return an item with probability proportional to its count.
- 012 · Track the user with the most distinct contacts Stream of (user, contact) pairs; answer top-1 in O(1) and top-k for a changing k.
Iterators, streams and counters
Small APIs over sequences that arrive one item at a time.
- 013 · Design a peeking iterator Wrap any iterator so peek() shows the next item without consuming it.
- 014 · Design a zigzag (cyclic) iterator over k lists Round-robin across k iterators, dropping exhausted ones.
- 015 · Design a flattening iterator over nested lists hasNext and next over arbitrarily nested lists, lazily, with a stack of iterators.
- 016 · Design a lazy tee: one iterator into n independent ones Each consumer sees every item once; buffer only what the slowest consumer has not read.
- 017 · Design independent level-order iterators over a shared tree next() returns one level; several iterators share one read-only tree; what if the tree mutates.
- 018 · Design a cursor-based pagination API Stable pages over a sorted dataset while rows are inserted and deleted.
- 019 · Design a running-median container add(num) and median() with two heaps, and the return type that trips candidates up.
- 020 · Design a hit counter hit(t) and getHits(t) over the last 300 seconds, then huge rates and concurrent calls.
- 021 · Design a logger rate limiter Print a message at most once per 10 seconds, then out-of-order timestamps and top-K messages.
- 022 · Design duplicate detection over sliding windows Flag repeats inside a window of a stream, then switch to a read-heavy query mode.
- 023 · Design a playlist shuffler with a no-repeat window next() is uniformly random among tracks not played in the last k calls; add back and repeat.
Schedulers, limiters and concurrency
Time, threads and shared resources inside one process.
- 024 · Design a rate limiter class isAllowed(clientId) for N requests per T, token bucket or sliding window, safe under threads.
- 025 · Design a billing-token rate limiter for AI agents Budgets in tokens rather than requests, per agent and per tenant, with refunds for failed calls.
- 026 · Design a task scheduler with dependencies and retries Run tasks when their dependencies finish, with priorities and exponential backoff.
- 027 · Design a concurrent priority task scheduler Submit with priority, cancel on timeout, many worker threads, no lost or duplicated runs.
- 028 · Design a timer that supports many concurrent timers Given a single-timer primitive, build addTimer(delay, callback) for thousands of timers.
- 029 · Design a stopwatch class start, pause, resume, reset and lap with a monotonic clock and an explicit state machine.
- 030 · Design a blocking connection pool acquire, release and activeCount; block when empty, no double release, leases against leaks.
- 031 · Build your own Future / CompletableFuture complete once, get with timeout, callbacks run exactly once, composable then().
- 032 · Design an in-process pub/sub event bus Topics, subscribers, delivery order, slow subscribers and unsubscribing during publish.
- 033 · Design a thread-safe singleton and justify the alternative Lazy, safe under races, testable, and why injecting one instance is usually better.
- 034 · Design a customer-support agent dispatcher Route requests to agents, handle agents taking breaks mid-request, re-queue fairly.
Parsers, editors and file systems
Text, trees and paths turned into objects.
- 035 · Design a text editor with undo and redo Cursor, insert, delete, undo, redo and batched undo on a document.
- 036 · Design a spreadsheet with formulas set_cell and get_cell with references to other cells, recalculation and cycle detection.
- 037 · Design an extensible spreadsheet aggregation API Add sum, max and new aggregates without duplicating traversal: init, accumulate, finalise.
- 038 · Design a JSON parser Tokenizer plus recursive descent into typed values, with useful error positions.
- 039 · Design a boolean and arithmetic expression library Classes and APIs for parsing, evaluating and simplifying expressions over variables.
- 040 · Design a streaming CSV importer with validation Read rows lazily, validate each with pluggable rules, report errors without stopping.
- 041 · Merge two configuration trees with per-node rules Deep-merge with strategies registered per path or type, open to new rules.
- 042 · Design a variable store with placeholder substitution set/get with %KEY% expansion, nested references and cycle protection.
- 043 · Design an HTTP router with path parameters Register patterns, resolve a path to a handler with precedence rules, add routes under traffic.
- 044 · Design an in-memory file system mkdir, addContent, readContent and ls over a tree of directories and files.
- 045 · Design a path-value file system API Create paths and store values with strict parent rules and invalid-path handling.
- 046 · Compute sizes and validate a hierarchical file system Total size of a node, detecting cycles, missing references and hard links, with memoisation.
Booking, allocation and simulators
Parking, elevators, rooms and seats.
- 047 · Design a parking lot Floors, spots and vehicle sizes, tickets and fees, extensible to new vehicle types.
- 048 · Design a multi-threaded parking lot Two cars arrive for the last spot at the same instant; allocate fairly without deadlock.
- 049 · Design an elevator controller N floors, one car, hall calls and car calls, SCAN scheduling and a state machine for doors.
- 050 · Design a multi-elevator dispatcher M cars, assignment strategies, peak traffic, fairness and a broken car.
- 051 · Design a meeting room reservation system Book, cancel and list with conflict detection, capacities and recurring meetings.
- 052 · Design calendar event conflict handling Overlap rules, recurrence, time zones and optimistic versioning for concurrent edits.
- 053 · Assign appointments to rooms Smallest free room id per appointment, then the busiest room: a scheduling API with the right structures.
- 054 · Design a restaurant waitlist join, leave and seat the first party that fits a freed table; one person with several reservations.
- 055 · Design a restaurant management system Tables, orders, kitchen queue, bills and tips as collaborating classes.
- 056 · Design a movie ticket booking system Shows, seats, holds that expire, payment and two users racing for one seat.
- 057 · Design a hotel booking system Room types, availability by date range, reservations and check-in.
- 058 · Design an airline reservation system Flights, seats, fares and itineraries with cancellations.
- 059 · Design a car rental system Vehicles, locations, reservations and pricing with late returns.
- 060 · Design a student-to-room allocation system Constraints and preferences, deterministic results and explainable rejections.
- 061 · Design a library management system Members, copies, loans, holds and fines.
- 062 · Design a course registration system Prerequisites, capacity, waitlists and schedule clashes.
- 063 · Design a train platform management system Assign platforms to arriving trains, delays and conflicts over time.
Games
Boards, pieces, rules and players.
- 064 · Design tic-tac-toe Board, players and O(1) win detection, then an n×n and an infinite grid.
- 065 · Design chess Pieces with polymorphic moves, check and checkmate, undo with Command.
- 066 · Design the Snake game move(direction) returning the score, a deque body and O(1) collision checks.
- 067 · Design Snake and Ladder Board, dice, players and turns, with jumps as data.
- 068 · Design 2048 Slide and merge rules, random spawns, win and lose detection.
- 069 · Design Minesweeper Mine placement without duplicates, cell state and recursive reveal.
- 070 · Design a deck of cards and Blackjack Cards, shuffling, hands, dealer rules and an extensible scoring interface.
- 071 · Design an object-oriented poker game Hands compared deterministically, betting rounds and a table of players.
- 072 · Design Monopoly Board squares with different behaviours, money, properties and turns.
- 073 · Design a game matchmaking system Queue players, pair by closest rating, time out and assign rooms.
- 074 · Design a leaderboard class addScore, top(k) and reset with a heap or a sorted structure behind a clean API.
Commerce and money
Carts, wallets, splits and matching engines.
- 075 · Design Splitwise Groups, expenses split equally, exactly or by percentage, balances and debt simplification.
- 076 · Design a digital wallet Accounts, transfers that never lose money, statements and limits.
- 077 · Design an ATM Card, PIN, withdraw and deposit as a state machine with cash dispensing.
- 078 · Design a payment processor Idempotent charges, transaction states, retries and refunds as commands.
- 079 · Design an order matching engine A limit order book with price-time priority, partial fills and cancels.
- 080 · Design an online stock brokerage Accounts, orders, positions and a watchlist with notifications.
- 081 · Design a vending machine States for idle, has-money and dispensing; inventory and change calculation.
- 082 · Design a coffee machine Recipes as data, ingredient inventory, concurrent orders on a few dispensers.
- 083 · Design an online shopping system Catalogue, cart, order and payment with discounts and inventory checks.
- 084 · Design a food delivery system Restaurants, orders, riders and assignment with order state transitions.
- 085 · Design an inventory management system Stock across warehouses, reservations and reorder thresholds under concurrent orders.
- 086 · Design a coupon and discount system Rules that stack or exclude, expiry and usage limits as composable specifications.
- 087 · Design an online auction Items, bids, a strict winner and concurrent bids at the deadline.
Applications and services
Feeds, loggers, notifications and small platforms modelled as classes.
- 088 · Design a logging framework Levels, formatters and sinks as a chain, thread-safe and non-blocking.
- 089 · Design a logger that returns its top-K messages Count messages over an interval and return the k most frequent, evicting the least important.
- 090 · Design a notification service Channels, templates, preferences, retries and idempotent sends in one process.
- 091 · Design a task management system (Trello-like) Boards, lists, cards, state transitions and watchers.
- 092 · Design a URL shortener (class level) Encoding strategies, a repository interface, caching and expiry in one process.
- 093 · Design a Twitter feed (class level) post, follow, unfollow and getNewsFeed merging the ten latest across followees.
- 094 · Design Stack Overflow Questions, answers, votes, comments, tags and reputation rules.
- 095 · Design an employee hierarchy with is_manager queries Reporting trees, peers and ancestor queries with the right precomputation.
- 096 · Design a role and permission system Users, roles, permissions and resource scopes with inheritance and denies.
- 097 · Design a rule and workflow engine Conditions and actions as objects, ordered evaluation, plugins registered at runtime.
- 098 · Design a traffic signal controller Phases as a state machine, timers and an emergency override.
- 099 · Design a music player Playlists, queue, shuffle and repeat modes as strategies, playback state.
- 100 · Design an in-process search index Tokenize documents, an inverted index, boolean queries and ranking.