167 of 167 ready to play
The playground
Every visualization and simulation on the site. Open one, change the input, break something, and step through what happens.
Foundations
Data Structures & Algorithms
Complexity Growth
Describe how running time and memory grow with input size using O, Ω and Θ.
Recurrences & Amortized Analysis
Analyze loops, recursion and amortized operations; solve recurrences with the Master Theorem.
Recursion Tree
Solve problems by defining them in terms of smaller instances of themselves: base cases, call stacks and recursion trees.
Tower of Hanoi
in Recursion
The lesson's hanoi(n, src, dst, via) running for real: watch each call park n - 1 disks on the spare peg, move disk n, then restack. The call stack never holds more than n + 1 frames.
Bit Manipulation Playground
AND, OR, XOR, shifts and the classic bit tricks for sets, parity and powers of two.
Sieve of Eratosthenes
Primes and the Sieve of Eratosthenes, GCD/LCM, modular arithmetic, fast exponentiation and combinatorics.
Euclid's GCD & Number Theory
in Math for DSA
Euclid's table for gcd(252, 105). Switch to Ext. GCD to watch x and y filled in on the way back up the recursion.
Fast Exponentiation
in Math for DSA
The same 3¹³ mod 7, one bit at a time. Try an exponent of 10¹⁸: it still takes only 60 iterations.
Pascal's Triangle (nCr mod m)
in Math for DSA
Each cell is the sum of the two cells above it, exactly as in the pascal function below. Add a modulus such as mod 6 to see a non-prime modulus work.
Linear Data Structures
Data Structures & Algorithms
Dynamic Array
Contiguous memory, O(1) indexing, and how dynamic arrays grow with amortized O(1) appends.
String Operations
Character encoding, immutability, common operations and the patterns behind string problems.
Linked List
Singly, doubly and circular lists: pointer manipulation, insertion, deletion and reversal.
Stack
Last-in, first-out: the structure behind undo, parsing, recursion and expression evaluation.
Expression Evaluation with a Stack
in Stacks
Convert an infix expression with shunting-yard, then press Evaluate it to run the postfix through an operand stack. Try 8 - 3 - 2 and 2 ^ 3 ^ 2 to see associativity break ties.
Queue & Deque
First-in, first-out queues, circular buffers and double-ended queues.
Hash Table
Hash functions, collisions, chaining vs open addressing, load factor and resizing.
Searching & Sorting
Data Structures & Algorithms
Linear Search
Scan every element until you find the target: the baseline every search is measured against.
Binary Search
Halve the search space every step: on sorted arrays, on answers, and on monotonic functions.
Bubble Sort
Repeatedly swap adjacent out-of-order pairs until the largest values bubble to the end.
Selection Sort
Select the minimum of the unsorted part and move it to the front, one position at a time.
Insertion Sort
Grow a sorted prefix by inserting each new element into its correct place, like sorting playing cards.
Merge Sort
Divide the array in half, sort each half recursively, then merge: guaranteed O(n log n).
Quick Sort
Partition around a pivot and recurse: the fastest general-purpose sort in practice.
Partitioning & Quickselect
in Quick Sort
Run Lomuto and Hoare on the same array (the lesson example is preloaded). Lomuto fixes the pivot at p; Hoare returns a split point j, and the last step compares both schemes' results and swap counts.
Three-Way Partition
in Quick Sort
One three-way partition on a duplicate-heavy array: watch lt, i and gt maintain the four regions from the table above, and note that i does not advance after a swap with gt.
Quickselect
in Quick Sort
Quickselect with Lomuto partitioning, exactly as described above: after each partition the pivot sits at its final index p, and everything on the side without k is discarded. Pick k with the slider and compare the comparison count with a full quick sort; try the Sorted input with pivot a[hi] to see the quadratic worst case. The implementation below uses Hoare partitioning instead, which narrows to [lo, j] or [j+1, hi] and stops when lo == hi.
Heap Sort
Build a max-heap, then repeatedly move the maximum to the end: O(n log n) in place.
Counting Sort
Beat the O(n log n) comparison bound by counting keys instead of comparing them.
Radix Sort
Sort digit by digit with a stable sub-sort, in O(d·(n + k)).
Trees
Data Structures & Algorithms
Tree Traversals
Nodes, edges, depth and height: the vocabulary of trees and the shape of binary trees.
Binary Search Tree
Left < node < right: search, insert and delete in O(h), and why height is everything.
AVL Tree
Self-balancing BSTs that keep heights within one using rotations.
Red-Black Tree
Color-based balancing rules that power TreeMap, std::map and the Linux scheduler.
Binary Heap
Complete binary trees stored in arrays: O(log n) insert and extract-min, O(n) heapify.
Trie (Prefix Tree)
Store strings character by character for lightning-fast prefix search and autocomplete.
Segment Tree
Answer range queries and point/range updates in O(log n), with lazy propagation.
Segment Tree with Lazy Propagation
in Segment Trees
The lazy-propagation implementation below, run on a = [2, 1, 5, 3, 4, 6, 0, 7]: range_add(1, 4, 10) stops at fully covered nodes and leaves violet tags, then query(3, 5) pushes a tag down before reading inside it (answer 33) and query(0, 7) returns the root's sum, 68.
Fenwick Tree
Prefix sums with point updates in O(log n) using the lowest set bit.
B-Tree
Wide, shallow, disk-friendly trees that power database indexes and file systems.
Graphs
Data Structures & Algorithms
Graph Representations
Vertices, edges, directed vs undirected, weighted graphs, and adjacency list vs matrix.
Breadth-First Search
Explore layer by layer with a queue: shortest paths in unweighted graphs.
Depth-First Search
Go deep before going wide: cycles, connectivity, and the backbone of many graph algorithms.
Topological Sort
Order the vertices of a DAG so every edge points forward: Kahn's algorithm and DFS ordering.
Dijkstra's Algorithm
Single-source shortest paths on non-negative weights with a priority queue.
Bellman-Ford & Floyd-Warshall
Shortest paths with negative edges, negative-cycle detection, and all-pairs shortest paths.
Minimum Spanning Trees
Connect every vertex at minimum cost with Kruskal's and Prim's algorithms.
Union-Find
Track connected components with near-constant-time union and find using path compression.
Grid Pathfinding
Heuristic-guided shortest paths: how games and maps find routes fast.
Strongly Connected Components
Kosaraju's and Tarjan's algorithms, plus finding the critical edges and vertices of a network.
Bridges and Articulation Points
in SCCs, Bridges & Articulation Points
The DFS from the table above, step by step: badges show disc/low (disc starts at 0), the side table tracks every vertex, and the two tests low[v] > disc[u] and low[v] ≥ disc[u] are checked after each child returns. Try the cycle (no bridges), the bow tie (root rule), parallel edges and a disconnected graph, or type your own edge list.
Problem-Solving Patterns
Data Structures & Algorithms
Two Pointers
Walk two indices toward or alongside each other to turn O(n²) scans into O(n).
Sliding Window
Maintain a moving window over a sequence for subarray and substring problems.
Prefix Sums & Difference Arrays
Precompute running totals for O(1) range sums, and difference arrays for O(1) range updates.
Floyd's Cycle Detection
Floyd's tortoise and hare: detect cycles, find midpoints and cycle entrances in O(1) space.
Monotonic Stack & Queue
Keep a stack or deque sorted to answer next-greater and sliding-maximum queries in O(n).
Largest Rectangle in Histogram
in Monotonic Stack & Queue
Each pop measures the popped bar's rectangle between the new stack top and i. The dashed green outline is the best so far, and the sentinel 0 at the end flushes the bars still waiting.
Trapping Rain Water (Stack)
in Monotonic Stack & Queue
Each pop adds one horizontal layer of water above the popped bar, capped by the shorter of its two walls. If the stack is empty after a pop, there is no left wall and the water spills.
Activity Selection
Make the locally optimal choice at every step, and know when that gives a global optimum.
Huffman Coding
in Greedy Algorithms
The same example step by step: the queue is drawn sorted, the first node extracted becomes the left (0) child, and ties go to the node that entered the queue first, exactly like the counter in the code below. Pick a text preset or type your own to see it encoded.
N-Queens
Systematically explore choices and undo them: permutations, subsets, N-Queens and Sudoku.
Backtracking: State-Space Tree
in Backtracking
The state-space tree grows as the search runs: each choose adds a node, each unchoose climbs back up. Switch to Permutations (the used array) or Combination sum, where sorted candidates let the search break off whole branches.
Dynamic Programming
Data Structures & Algorithms
Fibonacci: Memoization vs Tabulation
Overlapping subproblems and optimal substructure: memoization vs tabulation, from Fibonacci up.
0/1 Knapsack
0/1, unbounded and bounded knapsack, plus subset sum and coin change.
Coin Change
in Knapsack Problems
Fewest coins, one amount at a time: each coin c is tried as the last coin by reading dp[a − c], and last[a] records the winner so the coins can be rebuilt. The side panel compares the answer with greedy; try the "Greedy stuck" preset, where largest-first never reaches the amount at all.
Coin Change II
in Knapsack Problems
Each row is the ways array after one more coin joins. A cell reads the row above (combinations without the new coin) and its own row c to the left (combinations that already end in c, which is what lets a coin repeat). Switch to Permutations to run the same update with the loops swapped and watch the count grow to 9.
LCS & Edit Distance
Two-sequence DP: longest common subsequence, edit distance and the diff algorithm.
Longest Increasing Subsequence
The O(n²) DP and the elegant O(n log n) patience-sorting solution.
Grid & Path DP
Unique paths, minimum path sum and dungeon problems on 2D grids.
Advanced DP: Matrix Chain & Held-Karp
Interval DP, bitmask DP, DP on trees and state-machine DP.
Advanced Topics
Data Structures & Algorithms
KMP String Matching
Find patterns in text in linear time with failure functions and rolling hashes.
Rabin-Karp & Z-Algorithm
in String Matching (KMP, Rabin-Karp, Z)
The rolling hash with the implementation's B = 131 and M = 10⁹ + 7. The crafted preset yellow vs ifbank collides even with this large prime, and the M = 101 preset collides constantly: in both, only verification stops a false match.
Z-Algorithm
in String Matching (KMP, Rabin-Karp, Z)
The Z-algorithm on S = P + T without a separator. The first preset rebuilds the table above (aab + xaab). Watch positions inside the Z-box copy their value from the mirror i − l for free, while only characters past r are compared.
Skip List
Layered linked lists with express lanes: probabilistic O(log n) search.
LRU Cache
Combine a hash map and a doubly linked list for O(1) get and put with eviction.
Fundamentals
System Design
Requirements Drive the Design
Functional vs non-functional requirements, trade-offs, and a repeatable framework for design interviews.
Request Lifecycle
What happens when you type a URL: DNS, TCP, TLS, HTTP, rendering and everything in between.
TCP vs UDP
The OSI and TCP/IP models, IP addressing, TCP vs UDP and the three-way handshake.
HTTP/1.1 vs HTTP/2 vs HTTP/3
Methods, status codes, headers, HTTP/1.1 vs HTTP/2 vs HTTP/3, and how TLS secures it all.
Offset vs Cursor Pagination
Design clean, versioned, paginated APIs and choose between REST, GraphQL and gRPC.
Real-time Communication
Short polling, long polling, Server-Sent Events and WebSockets compared.
Estimation Calculator
Latency numbers every engineer should know, powers of two, and estimating QPS, storage and bandwidth.
Latency Numbers & Percentiles
in Back-of-the-Envelope Estimation
The same numbers on a log scale: each step is a different world.
Scaling to Millions
Vertical vs horizontal scaling, stateless services and the path from one server to millions of users.
Availability Calculator
Nines, SLAs/SLOs/SLIs, redundancy, failover, and computing availability of whole systems.
Building Blocks
System Design
DNS Resolution
How names become IP addresses: resolvers, root and TLD servers, record types, TTLs and GeoDNS.
Load Balancer
Distribute traffic across servers: algorithms, L4 vs L7, health checks and sticky sessions.
API Gateway Pipeline
Forward vs reverse proxies, and API gateways for routing, auth, rate limiting and aggregation.
Content Delivery Network
Serve content from the edge: push vs pull CDNs, cache keys, invalidation and edge compute.
Caching Strategies
Cache-aside, write-through, write-back, eviction policies, invalidation and stampede protection.
SQL vs NoSQL Data Models
Relational, key-value, document, wide-column and graph databases, and how to choose.
Database Indexing
B-tree and hash indexes, composite and covering indexes, and LSM trees vs B-trees.
Database Replication
Leader-follower, multi-leader and leaderless replication; sync vs async and replication lag.
Sharding & Partitioning
Split data across machines: range, hash and directory partitioning, hot spots and rebalancing.
Consistent Hashing
Place servers and keys on a ring so adding a node moves only K/N keys; virtual nodes for balance.
Message Queues & Consumer Groups
Decouple services with queues and logs: Kafka, RabbitMQ, consumer groups and backpressure.
Erasure Coding vs Replication
Store files at scale: S3-style object stores, block vs file vs object storage, and pre-signed URLs.
Inverted Index
Inverted indexes, tokenisation, TF-IDF/BM25 ranking and how Elasticsearch scales search.
Rate Limiting Algorithms
Token bucket, leaky bucket, fixed and sliding windows, and distributed rate limiting.
Snowflake IDs
UUIDs, database sequences, ticket servers and Twitter Snowflake IDs.
Distributed Systems
System Design
CAP Theorem & PACELC
During a partition you must choose consistency or availability, and latency trades off even without one.
Consistency Models
Linearizability, sequential, causal, read-your-writes and eventual consistency.
Isolation Levels & Anomalies
Transactions, isolation anomalies (dirty reads, phantoms, write skew) and MVCC.
Two-Phase Commit & Sagas
Two-phase commit, three-phase commit and the Saga pattern with compensating actions.
Raft Consensus
How a cluster agrees on one value: leader election, log replication and safety.
Quorum Reads & Writes
N, R and W: tunable consistency, sloppy quorums, hinted handoff and read repair.
Bloom Filter & Count-Min Sketch
Bloom filters, Count-Min Sketch and HyperLogLog: huge memory savings for a little uncertainty.
Gossip & Failure Detection
Detect failed nodes and spread cluster state epidemically, as Cassandra and Consul do.
Vector & Lamport Clocks
Why wall clocks lie: Lamport timestamps, vector clocks and hybrid logical clocks.
Delivery Semantics & Idempotency
At-most-once, at-least-once and effectively-once delivery, idempotency keys and deduplication.
Architecture Patterns
System Design
Monolith vs Microservices
When to split a system, how services communicate, and the costs of distribution.
Event Sourcing & CQRS
Build systems around events: choreography vs orchestration, CQRS read models and event stores.
Service Discovery
How services find each other: client vs server-side discovery, registries and sidecar proxies.
Circuit Breaker
Timeouts, retries with backoff and jitter, circuit breakers, bulkheads and graceful degradation.
Distributed Tracing
Logs, metrics and traces; RED/USE methods, distributed tracing and alerting on SLOs.
OAuth 2.0 & JWT
Sessions vs JWTs, OAuth 2.0 and OIDC, hashing passwords, and defending against common attacks.
Kubernetes Reconciliation
Docker, Kubernetes, autoscaling and deployment strategies like blue-green and canary.
MapReduce Word Count
MapReduce, Spark, Flink, windowing and the Lambda vs Kappa architectures.
Case Studies
System Design
News Feed Fan-out
Twitter/Instagram timelines: fan-out on write vs read, ranking and the celebrity problem.
Offset vs Cursor Pagination
in Design a News Feed
Scroll the feed with both kinds of pagination: new posts land on top between page requests, so the offset client's next page repeats posts it already showed, while the cursor client carries on from its last post. Delete a post to see offset pagination skip one instead.
Adaptive Bitrate Streaming
YouTube/Netflix: upload pipelines, transcoding, adaptive bitrate streaming and CDNs.
Geohash & Quadtree
Uber/Lyft: location updates, geohashes and quadtrees, matching drivers and surge pricing.
Duplicate Emails: At-Least-Once & Dedup
in Design a Notification System
The notification service publishes to Kafka, and an email worker sends through SES. Here the worker's offset commit is lost, so Kafka redelivers and at-least-once sends the same email twice. Switch to effectively-once: claim(delivery_id) finds the delivery already sent and skips it. Then pick "Worker crashes after sending": SES takes no idempotency key, so a crash between SES accepting the email and mark_sent still sends it twice, the window this section calls unavoidable.
Retry Storms: Backoff & Jitter
in Design a Notification System
A provider outage seen from the retry side: 300 sends fail at once and retry with a fixed delay, exponential backoff, or exponential backoff with full jitter. Fixed delays and plain exponential backoff send the retries back in synchronized waves many times the provider's capacity; full jitter spreads them out.
Chunking & Deduplication
Google Drive/Dropbox: chunking, deduplication, sync conflicts and metadata databases.
Idempotency Keys & Dedup Tables
in Design a Payment System
The "our service → processor" hop with a crash in the worst place: the worker charges the card, then dies before recording it. The redelivered message misses the dedup table, but the retry carries the same idempotency key, so the processor replays the original charge. Switch the guarantee to at-least-once to see the same fault charge the customer twice.
Seat Holds & Double Booking
Ticketmaster/BookMyShow: seat holds, high-contention inventory, virtual waiting rooms.
Lost Update (Double Booking)
in Design a Ticket Booking System
Double booking is a lost update: two transactions both read "available" and both write "held". It opens at Read Committed, where the race gets through. Switch the level to see which ones stop it, and how row locks make the second writer wait.
OOP & Design Principles
Design Patterns
Four Pillars of OOP
Encapsulation, abstraction, inheritance and polymorphism, and what each one buys you in real code.
Composition vs Inheritance
Why "has-a" usually beats "is-a": fragile base classes, and building behavior from small parts.
Interfaces & Abstract Classes
Program to an interface, not an implementation: contracts, abstract base classes and when to use each.
Reading UML Diagrams
The arrows and boxes every design discussion uses: associations, inheritance, composition and message flows.
SOLID Principles
Single responsibility, open/closed, Liskov substitution, interface segregation and dependency inversion.
Law of Demeter
Coupling and cohesion, and the everyday rules of thumb that keep a codebase small and changeable.
Creational Patterns
Design Patterns
Singleton Pattern
Exactly one instance with a global access point, and why it is the most misused pattern of all.
Factory Method Pattern
Let subclasses decide which concrete class to create, so callers depend only on an interface.
Abstract Factory Pattern
Create whole families of related objects (a light theme, a dark theme) without naming their classes.
Builder Pattern
Assemble complex objects step by step, and stop writing constructors with ten parameters.
Prototype Pattern
Create new objects by cloning a configured example: shallow vs deep copies and registries.
Object Pool Pattern
Reuse expensive objects such as connections and threads instead of creating them on every request.
Dependency Injection
Hand objects their collaborators instead of letting them build their own: testability and containers.
Structural Patterns
Design Patterns
Adapter Pattern
Make an incompatible interface fit the one your code expects, like a travel plug adapter.
Bridge Pattern
Split an abstraction from its implementation so both can vary without a class explosion.
Composite Pattern
Treat single objects and groups of objects the same way: trees of shapes, folders and menus.
Decorator Pattern
Add behavior to an object at runtime by wrapping it, stacking features without subclassing.
Facade Pattern
One simple entry point in front of a complicated subsystem.
Flyweight Pattern
Share the common state of thousands of similar objects to save memory.
Proxy Pattern
A stand-in that controls access to an object: lazy loading, caching, access checks and remote calls.
Behavioral Patterns
Design Patterns
Strategy Pattern
Swap an algorithm at runtime behind one interface instead of a growing if/else chain.
Observer Pattern
Let many objects react when one changes, without the subject knowing who they are.
Command Pattern
Turn a request into an object you can queue, log, undo and redo.
State Pattern
Let an object change its behavior when its internal state changes, as a clean state machine.
Template Method Pattern
Fix the skeleton of an algorithm in a base class and let subclasses fill in the steps.
Chain of Responsibility Pattern
Pass a request along a chain of handlers until one deals with it: middleware and approval flows.
Iterator Pattern
Walk a collection without exposing how it's stored, and why every language builds it in.
Mediator Pattern
Route communication through one hub so objects stop talking to each other directly.
Memento Pattern
Capture and restore an object's state without breaking encapsulation: snapshots and undo.
Visitor Pattern
Add new operations to a class hierarchy without changing the classes: double dispatch explained.
Interpreter Pattern
Represent a small language's grammar as classes and evaluate sentences in it.
Null Object Pattern
Replace null checks with an object that does nothing, safely.
Specification Pattern
Express business rules as small combinable objects: and, or, not.
Concurrency Patterns
Design Patterns
Producer-Consumer Pattern
Decouple threads that make work from threads that do it with a bounded blocking queue.
Thread Pool
Run many tasks on a fixed set of reusable worker threads, and size the pool sensibly.
Read-Write Lock
Let many readers in at once but give writers exclusive access, and the starvation trade-off.
Future & Promise
Represent a result that isn't ready yet: chaining, combining and handling failures.
Double-Checked Locking
Lazy initialization without locking on every call, and the memory-model trap that breaks it.
Anti-patterns & Refactoring
Design Patterns
Code Smells and Their Cures
God objects, primitive obsession, shotgun surgery and other smells, and the patterns that cure them.
Refactoring to Strategy
Step-by-step refactors from tangled code to Strategy, State and Factory, with tests keeping you safe.