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.

  1. Encapsulation Hiding data behind methods so an object's rules cannot be broken from outside.
  2. Abstraction and interfaces Describing what an object does, not how, so callers depend on a promise.
  3. Inheritance versus composition Being a kind of thing, or having a thing: when each is right.
  4. Polymorphism One call, many behaviours: the code that removes the if-else ladder.
  5. Value objects and immutability Objects defined by their value, never changed, safely shared.
  6. 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.

  1. Single responsibility One reason to change per class.
  2. Open-closed principle Add behaviour by adding code, not by editing what works.
  3. Liskov substitution A subclass must be usable wherever its parent is.
  4. Interface segregation Small interfaces so classes are not forced to fake methods.
  5. Dependency inversion and injection Depend on interfaces and receive collaborators from outside.
  6. Law of Demeter and tell-don't-ask Talk to your neighbours, not your neighbours' insides.
  7. DRY, KISS and YAGNI Remove duplication, keep it simple, build what is asked.

Creational patterns

How objects get made.

  1. Factory method and simple factory One place that decides which concrete class to create.
  2. Abstract factory A family of related objects created together.
  3. Builder Constructing a complex object step by step with readable code.
  4. Singleton and its alternatives Exactly one instance, and why dependency injection is usually better.
  5. Prototype and registries Cloning a configured object, or looking one up by name.
  6. Object pools Reusing expensive objects instead of making new ones.

Structural patterns

How objects are composed into bigger ones.

  1. Adapter Making an existing class fit the interface you need.
  2. Decorator Adding behaviour by wrapping, without subclass explosion.
  3. Composite Treating a tree of parts and wholes uniformly.
  4. Facade One simple front door to a complicated subsystem.
  5. Proxy A stand-in that controls access: lazy, cached, protected or remote.
  6. Flyweight Sharing the heavy, unchanging part of millions of small objects.
  7. Bridge Separating an abstraction from its implementation so both can vary.

Behavioral patterns

How objects talk and divide up work.

  1. Strategy Swapping an algorithm at runtime by passing an object.
  2. State machines and the State pattern Behaviour that depends on a mode, without a wall of conditionals.
  3. Observer and event listeners Telling interested objects something happened, without knowing who they are.
  4. Command Turning an action into an object you can queue, log and undo.
  5. Template method A fixed skeleton of steps with a few steps left to subclasses.
  6. Iterator and generators Walking a collection without exposing how it is stored.
  7. Chain of responsibility Passing a request along handlers until one takes it.
  8. Mediator One object that coordinates many, so they do not all know each other.
  9. Memento and undo Saving and restoring an object's state without breaking encapsulation.
  10. Visitor Adding operations over a class family without touching the classes.
  11. 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.

  1. From requirements to classes Nouns, verbs and the use-case walk that finds the classes.
  2. Relationships and multiplicity Association, aggregation, composition, and the numbers on the lines.
  3. Reading and drawing class diagrams The notation interviewers expect, and what to leave out.
  4. Designing method signatures Inputs, outputs, errors and names that make misuse hard.
  5. Errors, exceptions and validation Failing loudly at the boundary and never in the middle.
  6. Identity, equality and hashing When two objects are the same object, and when they are equal.
  7. Domain events Recording what happened as objects, so other parts can react later.
  8. 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.

  1. Hash map plus linked list (LRU) O(1) lookup and O(1) recency with two structures that point at each other.
  2. Heaps and priority queues in object design Scheduling, ranking and timers with a heap behind a clean interface.
  3. Tries behind prefix APIs Autocomplete and dictionary objects built on a character tree.
  4. Modeling boards and grids Cells, moves, win checks and bounds for games and simulators.
  5. Time, TTLs and expiry inside objects Injecting a clock, expiring entries lazily or with a timer wheel.
  6. Sliding windows and counters Rate limiters and hit counters as objects with bounded memory.
  7. Intervals and scheduling Meetings, bookings and conflicts as interval arithmetic.
  8. Graphs inside objects Dependencies, routes and social links as adjacency behind an API.
  9. Parsing and tokenizing Expressions, commands and file paths turned into structures.
  10. Snapshots and versioning Keeping history cheaply: copies, diffs and persistent structures.

Concurrency in one process

Making objects safe when many threads use them.

  1. Locks and mutexes Making a critical section one-at-a-time, and what it costs.
  2. Thread-safe collections and atomics Counters and maps many threads can share.
  3. Producer-consumer and bounded queues Decoupling threads with a queue that blocks when full or empty.
  4. Read-write locks Many readers at once, one writer alone.
  5. Deadlock and how to avoid it Lock ordering, timeouts and why two locks are twice the danger.
  6. Optimistic concurrency and versions Check-then-write with a version number instead of a lock.
  7. Executors, futures and timers Running work on a pool and getting the result back.
  8. Idempotent operations Making a repeated call harmless inside a single process too.

Quality, testing and extensibility

Proving it works and keeping it changeable.

  1. Designing for unit tests Seams, fakes and injected clocks that make a class testable.
  2. Extensibility points Deciding in advance what will change, and leaving one door for it.
  3. Naming and readability Code the interviewer can follow without you narrating.
  4. Trade-offs and over-engineering When a pattern is a cost, and how to say so.
  5. 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.

  1. 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.
  2. 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.
  3. 003 · Design a cache manager with pluggable eviction and TTL One cache class, eviction policy injected (LRU, LFU, FIFO), entries that expire on time.
  4. 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.
  5. 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.
  6. 006 · Design an in-memory database with transactions Tables, indexes and begin/commit/rollback in one process.
  7. 007 · Design a hash map and hash set from scratch Buckets, hashing, collisions and resizing, behind the familiar interface.
  8. 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.
  9. 009 · Design a set with O(1) insert, delete and getRandom An array plus an index map, with swap-with-last deletion.
  10. 010 · Design a phone book with concurrent access Add, lookup and prefix search over contacts, then make it safe for readers and writers.
  11. 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.
  12. 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.

  1. 013 · Design a peeking iterator Wrap any iterator so peek() shows the next item without consuming it.
  2. 014 · Design a zigzag (cyclic) iterator over k lists Round-robin across k iterators, dropping exhausted ones.
  3. 015 · Design a flattening iterator over nested lists hasNext and next over arbitrarily nested lists, lazily, with a stack of iterators.
  4. 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.
  5. 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.
  6. 018 · Design a cursor-based pagination API Stable pages over a sorted dataset while rows are inserted and deleted.
  7. 019 · Design a running-median container add(num) and median() with two heaps, and the return type that trips candidates up.
  8. 020 · Design a hit counter hit(t) and getHits(t) over the last 300 seconds, then huge rates and concurrent calls.
  9. 021 · Design a logger rate limiter Print a message at most once per 10 seconds, then out-of-order timestamps and top-K messages.
  10. 022 · Design duplicate detection over sliding windows Flag repeats inside a window of a stream, then switch to a read-heavy query mode.
  11. 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.

  1. 024 · Design a rate limiter class isAllowed(clientId) for N requests per T, token bucket or sliding window, safe under threads.
  2. 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.
  3. 026 · Design a task scheduler with dependencies and retries Run tasks when their dependencies finish, with priorities and exponential backoff.
  4. 027 · Design a concurrent priority task scheduler Submit with priority, cancel on timeout, many worker threads, no lost or duplicated runs.
  5. 028 · Design a timer that supports many concurrent timers Given a single-timer primitive, build addTimer(delay, callback) for thousands of timers.
  6. 029 · Design a stopwatch class start, pause, resume, reset and lap with a monotonic clock and an explicit state machine.
  7. 030 · Design a blocking connection pool acquire, release and activeCount; block when empty, no double release, leases against leaks.
  8. 031 · Build your own Future / CompletableFuture complete once, get with timeout, callbacks run exactly once, composable then().
  9. 032 · Design an in-process pub/sub event bus Topics, subscribers, delivery order, slow subscribers and unsubscribing during publish.
  10. 033 · Design a thread-safe singleton and justify the alternative Lazy, safe under races, testable, and why injecting one instance is usually better.
  11. 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.

  1. 035 · Design a text editor with undo and redo Cursor, insert, delete, undo, redo and batched undo on a document.
  2. 036 · Design a spreadsheet with formulas set_cell and get_cell with references to other cells, recalculation and cycle detection.
  3. 037 · Design an extensible spreadsheet aggregation API Add sum, max and new aggregates without duplicating traversal: init, accumulate, finalise.
  4. 038 · Design a JSON parser Tokenizer plus recursive descent into typed values, with useful error positions.
  5. 039 · Design a boolean and arithmetic expression library Classes and APIs for parsing, evaluating and simplifying expressions over variables.
  6. 040 · Design a streaming CSV importer with validation Read rows lazily, validate each with pluggable rules, report errors without stopping.
  7. 041 · Merge two configuration trees with per-node rules Deep-merge with strategies registered per path or type, open to new rules.
  8. 042 · Design a variable store with placeholder substitution set/get with %KEY% expansion, nested references and cycle protection.
  9. 043 · Design an HTTP router with path parameters Register patterns, resolve a path to a handler with precedence rules, add routes under traffic.
  10. 044 · Design an in-memory file system mkdir, addContent, readContent and ls over a tree of directories and files.
  11. 045 · Design a path-value file system API Create paths and store values with strict parent rules and invalid-path handling.
  12. 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.

  1. 047 · Design a parking lot Floors, spots and vehicle sizes, tickets and fees, extensible to new vehicle types.
  2. 048 · Design a multi-threaded parking lot Two cars arrive for the last spot at the same instant; allocate fairly without deadlock.
  3. 049 · Design an elevator controller N floors, one car, hall calls and car calls, SCAN scheduling and a state machine for doors.
  4. 050 · Design a multi-elevator dispatcher M cars, assignment strategies, peak traffic, fairness and a broken car.
  5. 051 · Design a meeting room reservation system Book, cancel and list with conflict detection, capacities and recurring meetings.
  6. 052 · Design calendar event conflict handling Overlap rules, recurrence, time zones and optimistic versioning for concurrent edits.
  7. 053 · Assign appointments to rooms Smallest free room id per appointment, then the busiest room: a scheduling API with the right structures.
  8. 054 · Design a restaurant waitlist join, leave and seat the first party that fits a freed table; one person with several reservations.
  9. 055 · Design a restaurant management system Tables, orders, kitchen queue, bills and tips as collaborating classes.
  10. 056 · Design a movie ticket booking system Shows, seats, holds that expire, payment and two users racing for one seat.
  11. 057 · Design a hotel booking system Room types, availability by date range, reservations and check-in.
  12. 058 · Design an airline reservation system Flights, seats, fares and itineraries with cancellations.
  13. 059 · Design a car rental system Vehicles, locations, reservations and pricing with late returns.
  14. 060 · Design a student-to-room allocation system Constraints and preferences, deterministic results and explainable rejections.
  15. 061 · Design a library management system Members, copies, loans, holds and fines.
  16. 062 · Design a course registration system Prerequisites, capacity, waitlists and schedule clashes.
  17. 063 · Design a train platform management system Assign platforms to arriving trains, delays and conflicts over time.

Games

Boards, pieces, rules and players.

  1. 064 · Design tic-tac-toe Board, players and O(1) win detection, then an n×n and an infinite grid.
  2. 065 · Design chess Pieces with polymorphic moves, check and checkmate, undo with Command.
  3. 066 · Design the Snake game move(direction) returning the score, a deque body and O(1) collision checks.
  4. 067 · Design Snake and Ladder Board, dice, players and turns, with jumps as data.
  5. 068 · Design 2048 Slide and merge rules, random spawns, win and lose detection.
  6. 069 · Design Minesweeper Mine placement without duplicates, cell state and recursive reveal.
  7. 070 · Design a deck of cards and Blackjack Cards, shuffling, hands, dealer rules and an extensible scoring interface.
  8. 071 · Design an object-oriented poker game Hands compared deterministically, betting rounds and a table of players.
  9. 072 · Design Monopoly Board squares with different behaviours, money, properties and turns.
  10. 073 · Design a game matchmaking system Queue players, pair by closest rating, time out and assign rooms.
  11. 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.

  1. 075 · Design Splitwise Groups, expenses split equally, exactly or by percentage, balances and debt simplification.
  2. 076 · Design a digital wallet Accounts, transfers that never lose money, statements and limits.
  3. 077 · Design an ATM Card, PIN, withdraw and deposit as a state machine with cash dispensing.
  4. 078 · Design a payment processor Idempotent charges, transaction states, retries and refunds as commands.
  5. 079 · Design an order matching engine A limit order book with price-time priority, partial fills and cancels.
  6. 080 · Design an online stock brokerage Accounts, orders, positions and a watchlist with notifications.
  7. 081 · Design a vending machine States for idle, has-money and dispensing; inventory and change calculation.
  8. 082 · Design a coffee machine Recipes as data, ingredient inventory, concurrent orders on a few dispensers.
  9. 083 · Design an online shopping system Catalogue, cart, order and payment with discounts and inventory checks.
  10. 084 · Design a food delivery system Restaurants, orders, riders and assignment with order state transitions.
  11. 085 · Design an inventory management system Stock across warehouses, reservations and reorder thresholds under concurrent orders.
  12. 086 · Design a coupon and discount system Rules that stack or exclude, expiry and usage limits as composable specifications.
  13. 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.

  1. 088 · Design a logging framework Levels, formatters and sinks as a chain, thread-safe and non-blocking.
  2. 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.
  3. 090 · Design a notification service Channels, templates, preferences, retries and idempotent sends in one process.
  4. 091 · Design a task management system (Trello-like) Boards, lists, cards, state transitions and watchers.
  5. 092 · Design a URL shortener (class level) Encoding strategies, a repository interface, caching and expiry in one process.
  6. 093 · Design a Twitter feed (class level) post, follow, unfollow and getNewsFeed merging the ten latest across followees.
  7. 094 · Design Stack Overflow Questions, answers, votes, comments, tags and reputation rules.
  8. 095 · Design an employee hierarchy with is_manager queries Reporting trees, peers and ancestor queries with the right precomputation.
  9. 096 · Design a role and permission system Users, roles, permissions and resource scopes with inheritance and denies.
  10. 097 · Design a rule and workflow engine Conditions and actions as objects, ordered evaluation, plugins registered at runtime.
  11. 098 · Design a traffic signal controller Phases as a state machine, timers and an emergency override.
  12. 099 · Design a music player Playlists, queue, shuffle and repeat modes as strategies, playback state.
  13. 100 · Design an in-process search index Tokenize documents, an inverted index, boolean queries and ranking.