The algorithms course you play.
A full data-structures-and-algorithms curriculum rebuilt as playable games. You drive each problem and lose to your own instincts, then meet the algorithm that never does — watch it work, predict its moves, and try to break it. The pseudocode, complexity, a worked trace and a quiz come after, once it's already clicked.
The roadmap
The whole course as one path — ordered from foundations to the hard, general topics. Follow it top to bottom, or jump straight to any unit.
- Unit 01 You are hereData StructuresThe containers everything else is built on — how you store data decides what’s fast.
- Unit 02 SearchingFind things fast by throwing away everything you don’t need to check.
- Unit 03 SortingPut data in order — the quiet prerequisite for half of all algorithms.
- Unit 04 Arrays & WindowsSqueeze O(n²) brute force down to O(n) with pointers and sliding windows.
- Unit 05 Strings & TextMatch, transform and index text without ever re-reading a character.
- Unit 06 GraphsThe universal model — maps, networks, dependencies, the web itself.
- Unit 07 Dynamic ProgrammingBreak a problem into overlapping subproblems and never solve one twice.
- Unit 08 GreedyTake the locally best choice and never look back — when that is provably enough.
- Unit 09 BacktrackingTry, fail, undo — search a space by exploring and retreating.
- Unit 10 Math & Number TheoryThe classic numeric algorithms every engineer should meet once.
New here? Follow the core track.
The 29 lessons that matter most, in the order to learn them — a single route from your first binary search to dynamic programming.
- 1 Binary Search: The VaultBeginner
- 2 The Closing Gap: Two PointersBeginner
- 3 The Dutch National Flag: Three-Way PartitionIntermediate
- 4 The Moving Frame: Sliding WindowBeginner
- 5 The Running Total: Prefix SumsBeginner
- 6 The Last One Standing: Boyer-Moore Majority VoteIntermediate
- 7 The Fair Draw: Reservoir SamplingIntermediate
- 8 The Instant Lookup: Hash TableBeginner
- 9 LIFO & FIFO: Stack & QueueBeginner
- 10 The Waiting Line: Monotonic StackIntermediate
- 11 The Ordered Tree: Binary Search TreeIntermediate
- 12 Express Lanes: The Skip ListAdvanced
- 13 How Databases Stay Balanced: B-TreesIntermediate
- 14 Two Nodes, Climbing to Meet: LCA with Binary LiftingAdvanced
- 15 Counting a Crowd in Kilobytes: HyperLogLogAdvanced
- 16 Sift Up, Sift Down: Heap & Priority QueueIntermediate
- 17 Merge Sort: The CascadeIntermediate
- 18 Quicksort: The Pivot PitIntermediate
- 19 Find the Kth Element: QuickselectIntermediate
- 20 Every Number Home: Cyclic SortIntermediate
- 21 BFS: The FloodBeginner
- 22 Build Order: DFS & Topological SortIntermediate
- 23 Cycles Into Components: Tarjan’s SCCAdvanced
- 24 Dijkstra: The Last MileBeginner
- 25 Pushing Water Through Pipes: Dinic’s Max-FlowAdvanced
- 26 The Best Streak: Kadane's AlgorithmIntermediate
- 27 The Fewest Coins: Coin ChangeIntermediate
- 28 The Loaded Bag: 0/1 KnapsackIntermediate
- 29 The Standoff: N-QueensIntermediate
How to use this hub
Play the lesson
Drive the algorithm yourself and lose — then watch it win. Intuition before formalism.
Read the theory
Pseudocode, complexity, a worked trace and a quiz — now that it has clicked.
Practice it
Solve the matching coding challenge in your browser, tests and all.
Keep it
Review the flashcards and the Big-O cheatsheet so it sticks for the interview.
Data Structures
The containers everything else is built on — how you store data decides what’s fast.
The Instant Lookup: Hash Table
Don't memorize the hash table — watch it drop keys into buckets. See a hash function scatter names across an array in O(1), then feed it a collision and watch two keys chain in the same bucket — the reason lookups are usually instant but degrade when the table fills. Hashing, collisions, chaining and the load factor — plus full theory, a runnable challenge and a quiz.
The Chain of Nodes: Linked List
Don't memorize the linked list — watch the pointers move. Insert at the head in O(1), delete a node by re-pointing around it, and reverse the whole list by flipping every arrow. Nodes, next-pointers and the O(n) walk — plus full theory, a worked trace and a quiz.
LIFO & FIFO: Stack & Queue
Don't memorize stacks and queues — watch them fill and drain side by side. A stack pushes and pops at the top (last in, first out); a queue adds at the back and removes at the front (first in, first out). The two O(1) containers behind undo, recursion, BFS and scheduling — plus full theory, a worked trace and a quiz.
The Ordered Tree: Binary Search Tree
Don't memorize the BST — watch it grow. Insert values (smaller left, larger right) so the tree stays sorted, search one path down in O(log n), then feed it sorted input and watch it collapse into a lopsided list — the reason self-balancing trees exist. Plus full theory, a worked trace and a quiz.
The Segment Tree
Don't memorize the segment tree — watch it answer ranges in log time. Each node stores an interval's sum, so a range-sum query combines a handful of covering nodes in O(log n), and a point update fixes one leaf and ripples to the root — also O(log n). The mutable cousin of the prefix sum — plus full theory, a worked trace and a quiz.
Bits Do the Walking: Fenwick Tree
Don't memorize the binary indexed tree — watch the bits do the walking. A Fenwick tree stores partial sums so a prefix-sum query and a point update both run in O(log n), using one trick: the lowest set bit i & -i tells each cell which range it owns. A query walks down, an update walks up. Plus full theory, a worked trace and a quiz.
Sift Up, Sift Down: Heap & Priority Queue
Don't memorize the heap — watch values sift up and down. A binary heap is a complete tree where every parent beats its children, so the max is always the root, stored in a plain array (node i has children 2i+1, 2i+2). Push appends and sifts up; pop takes the root and sifts down, both O(log n) — the engine behind priority queues, Dijkstra and heapsort. Plus full theory, a worked trace and a quiz.
The Tree That Rebalances Itself: AVL Tree
Don't memorize AVL rotations — watch the tree rebalance itself. An AVL tree is a binary search tree that tracks each node's balance factor and rotates the instant one tips to ±2: a single rotation for straight-line LL/RR leans, a double for LR/RL zigzags. That keeps height O(log n) forever, so search never decays. Plus full theory, a worked trace and a quiz.
Express Lanes: The Skip List
Don't memorize the skip list — ride its express lanes. A sorted linked list searches in O(n); stack a few sparse express lanes on top and search drops to O(log n) — matching a balanced tree, but built from coin flips instead of rotations. Watch a search skip across the top lane and descend to the value — plus full theory, the code and a quiz.
Two Nodes, Climbing to Meet: LCA with Binary Lifting
Don't memorize binary lifting — watch two tree nodes climb to meet. The lowest common ancestor is where two nodes' paths to the root first join; binary lifting stores each node's 2^k-th ancestor so you leap up the tree in powers of two, level the deeper node, then lift both together — LCA in O(log n) after O(n log n) preprocessing. Made playable, with theory and a quiz.
Counting a Crowd in Kilobytes: HyperLogLog
Don't memorize HyperLogLog — watch leading zeros count a crowd. Counting distinct items in a huge stream would need a set holding every one; HyperLogLog needs a few kilobytes. Hash each item, count the leading zeros, keep the longest run per bucket, and the harmonic mean of those runs estimates the cardinality within ~1%. The probabilistic sketch behind Redis PFCOUNT and approximate COUNT(DISTINCT) — made playable, with theory and a quiz.
How Databases Stay Balanced: B-Trees
Don't memorize B-trees — watch a node overflow and split. A B-tree keeps millions of keys sorted and shallow by packing many per node and splitting a full node in half, floating its median up to the parent. That's how database indexes and filesystems find any key in a handful of disk reads. Watch keys insert, nodes fill, and the tree grow upward — with theory and a quiz.
Searching
Find things fast by throwing away everything you don’t need to check.
Binary Search: The Vault
Don't memorize binary search — play it. Crack a vault of sorted dials, burn through guesses by instinct, then meet the Halver who throws away half the search space with every single look and finds any value in O(log n). Three acts — crack it, watch the window collapse, predict the midpoint.
Find the Peak by Thirds: Ternary Search
Don't memorize ternary search — watch the window shrink. When a function has a single peak, two probes at the one-third marks reveal which outer third can't hold the maximum, so you drop it and keep two-thirds. Repeat and the window collapses onto the peak in O(log n). See why it needs a unimodal shape, not a monotonic one. Plus full theory, a worked trace and a quiz.
Sorting
Put data in order — the quiet prerequisite for half of all algorithms.
Quicksort: The Pivot Pit
See quicksort actually work — then drive it. Watch the pivot partition an array in place, smaller-left and larger-right; pick your own pivot and feel how its position sets the balance; then feed it an already-sorted list and watch a fixed pivot melt down to O(n²) — and fix it with one random line. Three acts — watch the pivot, pick the pivot, break the worst case.
Merge Sort: The Cascade
Don't read about merge sort — play it. Watch single-element runs cascade upward into one sorted array, merge two sorted halves by hand by always taking the smaller front, then prove the payoff: O(n log n) on sorted, reversed and shuffled input alike — the guarantee quicksort can't make. Three acts — watch the cascade, merge two runs, prove the guarantee.
The Tournament: Heap Sort
Don't memorize heap sort — watch the tournament play out. See an array read as a binary tree, build it into a max-heap where every parent beats its children so the champion sits at the root, then pluck that root maximum to the end again and again as the sorted region grows from the right. Sift-down, the two phases, and why it's O(n log n) in place with no extra memory — plus full theory, a runnable challenge and a quiz.
No Comparisons: Counting & Radix Sort
Don't memorize counting sort — watch it sort without a single comparison. Tally how many times each value appears, then emit the values in order straight from the counts — O(n + k), the non-comparison sort that beats the O(n log n) barrier for bounded keys (and the stable pass inside radix sort). Plus full theory, a worked trace and a quiz.
Scatter, Sort, Gather: Bucket Sort
Don't memorize bucket sort — watch values fall into place. Scatter n values into k ordered buckets by value, sort each small bucket with a cheap insertion sort, then read the buckets left to right. Because the buckets are ordered, concatenation is already sorted — no merge. On uniform data it runs in O(n + k). Plus full theory, a worked trace and a quiz.
Find the Kth Element: Quickselect
Don't memorize quickselect — watch it throw away half the array each step. Find the kth-smallest element (or the median) without fully sorting: partition around a pivot, see which side the target rank falls in, and recurse into only that one. Average O(n) instead of O(n log n) — plus full theory, the code and a quiz.
Every Number Home: Cyclic Sort
Don't memorize cyclic sort — watch each number walk home. When an array holds the values 1..n scrambled, sort it in O(n) with no comparisons: swap the current element to the index it belongs at until it's home, then advance. The pattern behind find-the-missing-number and find-the-duplicate — plus full theory, the code and a quiz.
Arrays & Windows
Squeeze O(n²) brute force down to O(n) with pointers and sliding windows.
The Moving Frame: Sliding Window
Don't memorize the sliding window — watch it glide. Find the best sum of k consecutive numbers in one O(n) pass: as the frame slides, subtract the number leaving and add the number entering instead of re-summing. See the entering and leaving cells light up and the best window lock in — plus the fixed-vs-variable window theory, a runnable challenge and a quiz.
The Closing Gap: Two Pointers
Don't memorize the two-pointer trick — watch the gap close. On a sorted array, a left and right pointer converge to find a target pair: too big, pull right in; too small, push left out. It turns an O(n²) double loop into one O(n) pass — plus full theory, a worked trace and a quiz.
The Running Total: Prefix Sums
Don't memorize prefix sums — watch the running total build. Precompute cumulative sums once in O(n), then answer any range-sum query in O(1) with a single subtraction: sum(i..j) = P[j] − P[i−1]. The trick behind range problems and 2-D image sums — plus full theory, a worked trace and a quiz.
The Waiting Line: Monotonic Stack
Don't memorize the monotonic stack — watch it resolve. Find the next greater element for every item in one pass by keeping a stack that only ever decreases: when a taller bar arrives, it instantly resolves everything shorter waiting below it. The O(n) trick behind next-greater, daily temperatures, largest rectangle and more — plus full theory, the code, and a quiz.
The Dutch National Flag: Three-Way Partition
Don't memorize sort-colors — watch three pointers sort it. Arrange a row of 0s, 1s and 2s into three clean bands in a single in-place pass: swap 0s down to low, 2s up to high, leave 1s be. The elegant three-pointer partition — and the exact scheme that keeps quicksort fast on duplicates — plus full theory, the code and a quiz.
The Last One Standing: Boyer-Moore Majority Vote
Don't memorize the majority vote — watch the votes cancel out. Find the value that appears more than half the time in one pass with just two variables: keep a candidate, add for a match, cancel for a mismatch, and whoever survives is the majority. O(n) time, O(1) space, works on streams — plus full theory, the code and a quiz.
The Fair Draw: Reservoir Sampling
Don't memorize reservoir sampling — watch it stay fair. Pick one element uniformly at random from a stream of unknown length, holding just one slot: keep the i-th arrival with probability 1/i, and every element ends up equally likely. The one-pass, O(1)-space trick behind sampling logs and huge files — plus full theory, the code and a quiz.
Strings & Text
Match, transform and index text without ever re-reading a character.
The Non-Backtracker: KMP
Don't memorize KMP — watch the pattern slide. Find a pattern in a text in linear time by never re-reading a character: build the pattern's LPS failure table from its own repeats, then on a mismatch jump the pattern forward instead of restarting the text pointer. See the false start, the jump, and the match — plus the O(n+m) theory, a runnable challenge and a quiz.
The Word Tree: Trie
Don't memorize the trie — watch words grow into a tree. Insert CAT, CAR, CARD, and DOG letter by letter and see shared prefixes share a path, with a flag marking where each real word ends. Then search a word and a prefix by walking down from the root. The O(length) prefix tree behind autocomplete — plus full theory, a runnable challenge and a quiz.
The Rolling Hash: Rabin-Karp
Don't memorize Rabin-Karp — watch the hash roll. Find a pattern in text by hashing each window and comparing numbers, rolling the hash forward in O(1): drop the leaving char, add the entering one. On a hash match, verify the characters. The fingerprinting idea behind plagiarism and dedup — plus full theory, a worked trace and a quiz.
Slide the Z-Box: Z-Algorithm
Don't memorize the Z-algorithm — watch the Z-box slide. The Z-array records how far each position re-matches the prefix. A cached [l, r] window lets you mirror earlier answers for free and compare fresh characters only when extending past its edge — the trick that makes it O(n). Great for pattern search via P # T. Plus full theory, a worked trace and a quiz.
Let the Mirror Do the Work: Manacher’s Algorithm
Don't memorize Manacher's algorithm — watch the mirror do the work. Find the longest palindromic substring in O(n): insert separators so every palindrome is odd, then compute a radius at each center, reusing a mirror inside the cached rightmost palindrome [C, R] and expanding only past its edge. The palindrome twin of the Z-algorithm. Plus full theory, a worked trace and a quiz.
One Pass, Every Word: Aho-Corasick
Don't memorize Aho-Corasick — watch one pass catch every pattern. Searching a text for a whole dictionary one word at a time is slow; Aho-Corasick builds a trie of the patterns, wires failure links that say where to fall back on a mismatch, and scans the text once — finding every occurrence of every pattern in O(text + matches). The multi-pattern generalization of KMP behind intrusion detection and virus scanners — made playable, with theory and a quiz.
Graphs
The universal model — maps, networks, dependencies, the web itself.
Dijkstra: The Last Mile
Don't watch Dijkstra's algorithm — play it. Drive a courier through a living isometric city, lose the fastest route to your own instincts, then meet the Dispatcher who floods the streets to find the optimal path every time. Four acts: drive it, watch the frontier, predict the next lock, then break it with a negative cycle.
BFS: The Flood
Don't memorize breadth-first search — play it. Find your own way through a maze, then release the flood that spreads from the start in rings and touches the exit by the shortest path every time, then watch depth-first search dive deep and miss it. Three acts — navigate it, release the flood, BFS vs DFS.
A* Search: The Ascent
Don't memorize A* — fly it. Orbit a real 3D mountain, climb it by instinct, then meet the Pathfinder who folds one optimistic guess into Dijkstra's flood so the whole search leans straight at the summit. Four acts in live 3D — climb it, watch the heuristic beat the blind flood, predict the lowest-f pop, then break optimality with a heuristic that lies.
Build Order: DFS & Topological Sort
Don't memorize topological sort — play it. Schedule eight interdependent build tasks by hand and feel the constraints bite, then let a depth-first search dive to the bottom of every dependency and surface a valid build order by reversing its finish times. Three acts — schedule it yourself, watch DFS reverse-post-order it, then add one bad edge and watch it detect the cycle and refuse.
Six Degrees: Union-Find
Don't memorize the Disjoint Set Union — play it. Wire up nine strangers one handshake at a time and watch separate friend circles merge into one, hit a redundant connection and see it refuse to close a cycle, then click any node to run find and watch path compression flatten the tree so the next lookup is instant. Union by rank, path compression and the near-constant O(α(n)) that powers Kruskal's MST — plus full theory, a runnable challenge and a quiz.
The Cheapest Grid: Kruskal's MST
Don't memorize Kruskal's algorithm — watch it wire up a network. Connect eight towns for the least total cable by always laying the cheapest edge that doesn't close a loop, with Union-Find rejecting cycles on the fly and the minimum spanning tree turning green edge by edge. Greedy choice, the cut property, and O(E log E) — plus full theory, a runnable challenge and a quiz.
The Patient Router: Bellman-Ford
Don't memorize Bellman-Ford — watch the distances settle. Find shortest paths from one source even with negative edge weights by relaxing every edge round after round until nothing improves, then one extra pass to catch a negative cycle. See why Dijkstra's greedy commit breaks on negatives while Bellman-Ford's patience doesn't — O(V·E), plus full theory, a runnable challenge and a quiz.
Every Vertex a Stepping Stone: Floyd–Warshall
Don't memorize Floyd–Warshall — watch the distance matrix improve. Three nested loops let every vertex act as an intermediate, one at a time, until dist[i][j] holds the shortest path between every pair. See each relaxation: is i → k → j cheaper than what we knew? Plus full theory, a worked trace and a quiz.
Grow the Cheapest Tree: Prim’s MST
Don't memorize Prim's algorithm — watch the tree grow. Prim builds a minimum spanning tree from one vertex, each step greedily adding the cheapest edge crossing from the tree to the outside via a min-heap of frontier edges. The cut property proves the greedy grab is always safe. Plus full theory, a worked trace and a quiz.
Cycles Into Components: Tarjan’s SCC
Don't memorize Tarjan's algorithm — watch cycles collapse into components. A strongly connected component is a maximal group of nodes that can all reach each other; Tarjan finds every one in a single depth-first pass using two numbers per node — a discovery time and a low-link — popping a component off a stack the moment a cycle's root is found, in O(V+E). Made playable, with theory and a quiz.
Pushing Water Through Pipes: Dinic’s Max-Flow
Don't memorize Dinic's algorithm — watch flow saturate a network. Given pipes with capacities, how much can flow from source to sink? Dinic layers the graph by shortest distance with a BFS, then floods every shortest augmenting path at once with a DFS blocking flow — repeating in O(V²E). The fast max-flow / min-cut engine behind matching, scheduling, and image segmentation — made playable, with theory and a quiz.
Dynamic Programming
Break a problem into overlapping subproblems and never solve one twice.
The Typo Fixer: Edit Distance
Don't memorize edit distance — watch the grid fill in. See how many insert, delete, and replace edits turn kitten into sitting, as a dynamic-programming table computes each cell from its diagonal, up, and left neighbors, then traces the cheapest path of edits back through the grid. The Levenshtein recurrence, match-is-free, and O(m·n) — plus full theory, a runnable challenge and a quiz.
The Best Streak: Kadane's Algorithm
Don't memorize Kadane's algorithm — watch the best streak emerge. Find the maximum-sum contiguous subarray in one pass: keep a running sum, drop it the moment it turns negative, and remember the best. The elegant O(n) DP one-liner — plus full theory, a worked trace and a quiz.
The Loaded Bag: 0/1 Knapsack
Don't memorize the knapsack DP — watch the table fill. Maximize value under a weight limit: each cell asks take it or leave it, dp[i][w] = max(leave, value + dp[i-1][w-weight]). Fill the grid, then trace back which items were picked. The canonical DP table — plus full theory, a worked trace and a quiz.
The Fewest Coins: Coin Change
Don't memorize coin change — watch the table fill. Find the fewest coins that make an amount by building the best answer for every amount up from 0: dp[a] = 1 + min over coins of dp[a-coin]. See why grabbing the biggest coin (greedy) fails and DP gets it right — plus full theory, a worked trace and a quiz.
The Longest Climb: Longest Increasing Subsequence
Don't memorize the LIS — watch it build. For each element, the longest increasing run ending there is one plus the best run ending on an earlier, smaller element: dp[i] = 1 + max(dp[j] for j<i, A[j]<A[i]). Fill the table, then trace the longest chain. The classic O(n²) DP (with an O(n log n) patience-sort trick) — plus full theory, a worked trace and a quiz.
Fill the Grid, Walk It Back: Longest Common Subsequence
Don't memorize LCS — watch the table fill, then walk it backwards. On a character match a cell extends the diagonal by one; on a mismatch it copies the better of up or left. Fill the grid and the corner holds the length; backtrack along the diagonals to recover the actual subsequence. The same table as edit distance. Plus full theory, a worked trace and a quiz.
Halving the Exponential: Meet in the Middle
Don't memorize meet-in-the-middle — watch two halves shake hands. Subset-sum over n items is 2^n by brute force; split the set in half, enumerate each half's 2^(n/2) subset sums, and match complements across the gap to hit your target. The square-root speedup that turns 2^40 into 2^20 — plus full theory, the code and a quiz.
Greedy
Take the locally best choice and never look back — when that is provably enough.
Frequent Symbols, Short Codes: Huffman Coding
Don't memorize Huffman coding — watch the tree assemble itself. Give frequent symbols short codes and rare ones long codes, with no code a prefix of another. Huffman builds the optimal such code greedily: merge the two least-frequent nodes with a min-heap until one tree remains, then read each code off its root-to-leaf path. The entropy stage inside zip, JPEG and MP3. Plus full theory, a worked trace and a quiz.
Finish First, Fit the Most: Interval Scheduling
Don't memorize activity selection — watch the greedy choice pay off. To fit the most non-overlapping intervals on one resource, sort by earliest finish time and take each interval that starts after the last one you took ends. Finishing soonest leaves the most room — which is why this beats sorting by shortest or earliest start, and is provably optimal. Plus full theory, a worked trace and a quiz.
Backtracking
Try, fail, undo — search a space by exploring and retreating.
The Standoff: N-Queens
Don't memorize backtracking — watch it try, clash, and undo. Place queens on a board so none attack each other, one column at a time: try a safe row, recurse, and when a column has no safe square, back up and move the previous queen. See placements go down, conflicts flash red, and the search backtrack its way to a solution — plus the pruning theory, a runnable challenge and a quiz.
Push, Recurse, Pop: Subsets by Backtracking
Don't memorize backtracking — watch the decision tree grow and unwind. To list every subset, treat each element as include-or-skip; every node you visit is a subset, and finishing a branch pops the last choice to try the next. That push-recurse-pop rhythm powers subsets, permutations, N-Queens and Sudoku. Plus full theory, a worked trace and a quiz.
Cut the Dead Branches: Combination Sum
Don't memorize combination sum — watch the dead branches get cut. Given reusable candidates, find every combination that adds to a target. Backtracking explores the choices, but the point is pruning: the instant a pick would overshoot what remains, that whole branch is abandoned. See how a bound turns an exponential search fast. Plus full theory, a worked trace and a quiz.
Guess, Hit a Wall, Erase: Sudoku Solver
Don't memorize the Sudoku solver — watch it guess, hit a wall and erase. Scan for the first empty cell, try each digit legal in its row, column and box, place it and recurse. When a cell has no legal digit, backtrack: undo the last placement and try the next. The same push-recurse-pop skeleton, now steered by constraints. Played on a 4×4 board, with theory and a quiz.
Math & Number Theory
The classic numeric algorithms every engineer should meet once.
Sieve of Eratosthenes: Prime Time
Find every prime under 100 without dividing once. Hit play and watch the multiples fall away in cheerful waves while the primes light up gold — whatever's left standing is prime. A playable take on the 2,000-year-old sieve, with the theory, a worked example and a quiz.
The Biggest Tile That Fits: Euclidean GCD
Don't memorize the Euclidean algorithm — see it as tiling. The greatest common divisor is the side of the largest square that fills the two numbers' rectangle with no gap. Peel the biggest square that fits, tile the leftover strip, repeat — that is exactly gcd(a, b) = gcd(b, a mod b), in O(log n). Plus full theory, a worked trace and a quiz.
Climb in Doubling Jumps: Modular Exponentiation
Don't memorize fast power — watch the exponent climb in doubling jumps. To compute a^b mod m you square the base to reach a, a², a⁴, a⁸ …, and multiply in only the powers the binary digits of b select. That is O(log b) multiplications instead of b, with the mod every step keeping numbers small — the engine behind RSA. Plus full theory, a worked trace and a quiz.
Fibonacci Fast-Forwarded: Matrix Exponentiation
Don't memorize matrix exponentiation — watch it fast-forward. The n-th Fibonacci number is the top of a 2×2 matrix raised to the n-th power, and repeated squaring raises a matrix to a huge power in O(log n) instead of O(n). Read the exponent in binary, square the base, fold it into the result on set bits — plus full theory, the code and a quiz.
Consistent Hashing: The Ring
Don't memorize consistent hashing — play the ring. Place servers and keys on a hash ring where each key belongs to the next server clockwise, add a node and watch only ~1/N of the keys move instead of nearly all (as hash % N would), then flip on virtual nodes to smooth a lopsided load. The sharding primitive behind caches, databases, and load balancers — made playable, with theory and a quiz.
Bloom Filter: Maybe Yes, Never No
Don't memorize the Bloom filter — play it. Add items by lighting k bits with k hashes, then query: all bits set means 'probably present', any bit unset means 'definitely absent'. Hunt down a live false positive and see why a Bloom filter can give a false yes but never a false no — the tiny, key-less probabilistic set behind caches, databases, and crawlers. Made playable, with theory and a quiz.
Count–Min Sketch: Counting in Tiny Space
Don't memorize the Count–Min Sketch — play it. Count how often items appear in a stream using a fixed grid of counters and d hashes: bump one cell per row on each event, and estimate a frequency by taking the minimum across rows. Watch a collision inflate an estimate, and see why it can over-count but never under-count — the structure behind heavy-hitters and streaming analytics. Made playable, with theory and a quiz.
Fisher–Yates: The Fair Shuffle
Don't memorize the Fisher–Yates shuffle — play it. Walk the array from the back, swap each element with a random one from the unshuffled front, and watch a provably uniform permutation build in O(n). Then see why the tempting naive shuffle (swap each slot with any random index) is silently biased. The one correct way to shuffle — made playable, with theory and a quiz.
Radix Sort: Sorting Without Comparing
Don't memorize radix sort — play it. Sort numbers by distributing them into 10 buckets by their last digit, gather, then repeat for each higher digit — with zero comparisons. Watch a stable pass per digit sort n numbers in O(n·d), and see why the passes must run least-significant digit first. Made playable, with theory and a quiz.
Bidirectional BFS: Meet in the Middle
Don't memorize bidirectional BFS — play it. Run two breadth-first searches at once, one forward from the start and one backward from the goal, and stop the instant their frontiers touch. Watch two small explored regions meet in the middle instead of one huge one, cutting explored nodes from roughly b^d toward 2·b^(d/2). Made playable, with theory and a quiz.
Morris Traversal: Threading the Tree
Don't memorize Morris traversal — play it. Walk a binary tree in sorted order using O(1) extra space by temporarily threading each node's inorder predecessor back to it, then undoing the thread on the way back — no stack, no recursion. Watch the threads appear and vanish as the tree is traversed in place and left exactly as it started. Made playable, with theory and a quiz.
LSM-Tree: Write Fast, Merge Later
Don't memorize the LSM-tree — play it. Writes land instantly in an in-memory memtable; when it fills, it flushes to an immutable sorted file (SSTable) on disk. Reads check the memtable then the SSTables newest-first, and compaction merges files while dropping shadowed old versions. The write-optimized engine behind RocksDB, Cassandra, and LevelDB — made playable, with theory and a quiz.
Convex Hull: Wrapping the Points
Don't memorize the convex hull — play it. Sort points left to right, then sweep once building a lower chain and once building an upper chain, popping any point that makes a non-left turn — the cross product decides every turn. Andrew's monotone chain finds the tightest enclosing polygon in O(n log n). Made playable, with theory and a quiz.
External Merge Sort: Bigger Than Memory
Don't memorize external merge sort — play it. When the data is too big for RAM, sort it in two phases: read chunks that fit in memory, sort each and write it back as a sorted run, then k-way merge all the runs by repeatedly emitting the smallest current head. The disk-based sort behind databases and big-data engines — made playable, with theory and a quiz.
Eulerian Path: Every Edge, Once
Don't memorize Hierholzer's algorithm — play it. An Eulerian path uses every edge of a graph exactly once, and exists only when 0 or 2 vertices have odd degree. Hierholzer builds it in O(E): walk unused edges until stuck, then splice in side-loops from any vertex with edges left. Watch the trail form and the degree rule decide whether it can — made playable, with theory and a quiz.
MinHash: Similarity in a Signature
Don't memorize MinHash — play it. Estimate the Jaccard similarity of two sets by comparing k tiny hash-based signatures: for each hash, the minimum value over a set's elements matches between two sets with probability equal to their Jaccard similarity. Add hash functions and watch the estimate converge on the true overlap. The trick behind near-duplicate detection at web scale — made playable, with theory and a quiz.
Line Sweep: Sliding the Line
Don't memorize the line sweep — play it. Slide an imaginary line across the input and handle a sorted list of events as it passes: +1 when an interval starts, −1 when it ends. A running counter reveals the maximum overlap (the 'meeting rooms' answer) in O(n log n). The sweep-line technique behind interval, overlap, and computational-geometry problems — made playable, with theory and a quiz.
Miller–Rabin: Probably Prime
Don't memorize Miller–Rabin — play it. Test whether a huge number is prime without factoring it: pick bases and check a chain of modular squares. A single failing base proves the number composite with certainty; passing k bases makes it prime with error at most 4⁻ᵏ. Watch a Carmichael number get caught and a pseudoprime fool the first bases before it's exposed — made playable, with theory and a quiz.
Karatsuba: Three, Not Four
Don't memorize Karatsuba — play it. Split two numbers in half and the schoolbook method needs four sub-multiplications; Karatsuba computes the same product with only three, using one clever combination. Recursing that trick drops multiplication from O(n²) to about O(n^1.585). Watch the three products form and combine — made playable, with theory and a quiz.
Tree DP: Answers Flow Up
Don't memorize tree DP — play it. Solve problems on a tree by computing each node's answer from its children in one post-order pass. Here: the maximum-weight independent set — pick nodes with the largest total weight, no two adjacent — by keeping two values per node (best if you take it, best if you don't). Watch the values flow up from the leaves and the optimal set light up — made playable, with theory and a quiz.
Bridges & Articulation Points: The Weak Links
Don't memorize Tarjan's bridge-finding — play it. A bridge is an edge whose removal disconnects the graph; an articulation point is such a vertex. One DFS, tracking each node's discovery time and the earliest ancestor its subtree can reach (its low-link), finds them all in O(V+E). Watch the DFS assign disc and low values and the critical edges light up — made playable, with theory and a quiz.
Simulated Annealing: Cool to Improve
Don't memorize simulated annealing — play it. Optimize a hard problem (a traveling-salesman tour) by proposing small random changes: always accept improvements, but sometimes accept a worse move too — with a probability that shrinks as a 'temperature' cools. Early heat escapes local minima; late cooling settles into a great solution. Watch the tour untangle as the temperature drops — made playable, with theory and a quiz.
Extended Euclidean & CRT: gcd, and a Bonus
Don't memorize the extended Euclidean algorithm — play it. It finds gcd(a,b) and, for free, the integers x and y with a·x + b·y = gcd — the Bézout coefficients that give modular inverses and power the Chinese Remainder Theorem. Watch the coefficient table build row by row and the identity a·x + b·y = gcd hold at every step — made playable, with theory and a quiz.
Pollard's Rho: Factor by Collision
Don't memorize Pollard's rho — play it. Factor a composite number without trial division by iterating a pseudo-random function mod n until two runners collide, then taking a gcd to reveal a factor. The sequence loops into a ρ shape — a tail leading into a cycle — which is where the algorithm gets its name. Watch the tortoise and hare meet and a factor pop out — made playable, with theory and a quiz.
Sqrt Decomposition: Blocks of Root-N
Don't memorize sqrt decomposition — play it. Split an array into blocks of size √n and precompute each block's answer. A range query then touches only a few whole blocks plus the partial ends — O(√n) instead of O(n) — and a point update fixes one element and its block. The simplest fast-range-query structure — made playable, with theory and a quiz.
Lazy Segment Tree: Update Lazily
Don't memorize lazy propagation — play it. A segment tree answers range queries in O(log n), but a range update that hits every leaf would be O(n). Lazy propagation fixes that: mark a handful of covering nodes with a pending 'lazy' tag and push it down to children only when a later query actually needs it. Watch a range-add tag O(log n) nodes instead of touching every leaf — made playable, with theory and a quiz.
Bitmask DP: Sets as Integers
Don't memorize bitmask DP — play it. Encode a set of visited items as the bits of an integer, and dynamic-program over (subset, position) states. On the traveling salesman problem this is the Held–Karp algorithm: O(2ⁿ·n²) instead of O(n!) — turning an intractable factorial search into an exponential one that's vastly smaller for real n. Watch subsets fill in as binary masks and the optimal tour emerge — made playable, with theory and a quiz.
Interval Tree: What Contains This?
Don't memorize the interval tree — play it. Store intervals in a BST keyed by their low endpoint and augment each node with the maximum endpoint in its subtree. A 'stabbing' query — which intervals contain point q — then prunes whole subtrees using that max, answering in O(log n + k) instead of scanning them all. Watch the search skip subtrees that can't possibly overlap — made playable, with theory and a quiz.
Suffix Array: Suffixes, Sorted
Don't memorize the suffix array — play it. Sort all suffixes of a string and store their starting positions; the result powers fast substring search, longest-repeated-substring, and more, in a fraction of a suffix tree's memory. Add the LCP array — the shared prefix between neighbours — and you unlock even more. Watch the suffixes sort and the shared prefixes light up — made playable, with theory and a quiz.
Digit DP: Count by Digits
Don't memorize digit DP — play it. Count how many numbers from 0 to N satisfy a digit property (like a target digit sum) without checking each one. Build them digit by digit, tracking a 'tight' flag that says whether the prefix still hugs N's own digits. Watch the count assemble position by position instead of looping to a billion — made playable, with theory and a quiz.
Treap: Balance by Chance
Don't memorize the treap — play it. It's a binary search tree and a heap at once: each node has a key (BST-ordered) and a random priority (heap-ordered). Since the shape is decided by random priorities, not insertion order, the tree stays balanced in expectation with no complicated rebalancing rules — just rotations. Watch keys insert and rotate into a balanced tree — made playable, with theory and a quiz.
Splay Tree: Touch It, Lift It
Don't memorize the splay tree — play it. Every time you touch a node, it rotates all the way up to the root — so recently and frequently accessed keys stay near the top and become cheap to reach again. No balance factors or colors, just splaying, with O(log n) amortized operations. Watch each access reshape the tree and pull the key to the root — made playable, with theory and a quiz.
Mo's Algorithm: Reorder to Win
Don't memorize Mo's algorithm — play it. Given many offline range queries, answer them by keeping one running window and sliding its two ends with cheap add/remove steps. The trick is the order: sort queries by their left endpoint's √n block, and total pointer movement collapses from O(q·n) to O((n+q)·√n). Watch reordering shrink the work — made playable, with theory and a quiz.
Timsort: Sort What's Already There
Don't memorize Timsort — play it. The default sort in Python and Java finds the natural sorted 'runs' already present in real data, extends short ones with insertion sort, then merges the runs with a smart stack — so nearly-sorted input sorts in nearly O(n). Watch the runs get detected and merged into a fully sorted array — made playable, with theory and a quiz.
Min-Cost Max-Flow: Cheapest Flow First
Don't memorize min-cost max-flow — play it. Every edge has a capacity and a per-unit cost; you want the maximum flow from source to sink at the least total cost. The method: repeatedly find the cheapest augmenting path (a shortest path by cost in the residual graph) and push flow along it. Watch flow accumulate along the cheapest routes first — made playable, with theory and a quiz.
Hungarian Algorithm: The Perfect Match
Don't memorize the Hungarian algorithm — play it. Given a cost matrix of workers × tasks, find the assignment of one worker per task that minimizes total cost, without trying all n! matchings. Subtract each row's minimum, then each column's, so zeros mark the cheapest options — then pick n independent zeros. Watch the matrix reduce and the optimal assignment appear — made playable, with theory and a quiz.
FFT: Values, Not Coefficients
Don't memorize the FFT — play it. Multiplying two polynomials by their coefficients is O(n²), but multiplying them as sampled values is just O(n) pointwise. The Fast Fourier Transform converts between coefficient form and value form in O(n log n) by evaluating at the roots of unity via divide-and-conquer — so polynomial multiplication and convolution drop from O(n²) to O(n log n). Watch the multiply pipeline run — made playable, with theory and a quiz.
Persistent Segment Tree: Every Version Kept
Don't memorize the persistent segment tree — play it. An ordinary update destroys the old state; a persistent one keeps every past version by copying only the O(log n) nodes on the update path and sharing everything else. So you can query the array as it was at any moment in history, using O(log n) extra memory per update. Watch an update copy just one root-to-leaf path — made playable, with theory and a quiz.
Red-Black Tree: Balance in Two Colors
Don't memorize the red-black tree — play it. It keeps a binary search tree balanced by painting nodes red or black and enforcing a few color rules that bound the height to O(log n). Every insertion adds a red node, then restores the rules with recolorings and at most a couple of rotations. Watch keys insert and the tree recolor and rotate itself back into balance — made playable, with theory and a quiz.
Piece Table & Rope: Edit Without Copying
Don't memorize the piece table — play it. Text editors don't re-copy a whole document on every keystroke. A piece table keeps the original text read-only, appends all new text to a separate add buffer, and describes the document as a list of 'pieces' that point into the two buffers. Inserting just splits a piece — no big copy, and undo is trivial. Watch an edit split a piece — made playable, with theory and a quiz.
Greedy vs Dynamic Programming: When Is Greedy Safe?
Don't guess which technique a problem needs — play both. Fill a 6-unit track from coins {1, 3, 4}: greedy grabs the 4, then needs two 1s, and finishes in 3 coins. The DP table finds 3 + 3 and finishes in 2. Same problem, and greedy is provably wrong. Then swap the coin set and watch greedy become optimal again — because the lesson isn't the counterexample, it's the condition. Three acts: play greedy, watch the table fill, then break it and fix it.
The patterns underneath
Individual algorithms are worth learning, but the real prize is the handful of patterns they share — the moves that unlock unfamiliar problems in an interview.
Divide & Conquer
Split in half, solve, combine — binary search, merge sort, quicksort.
Two Pointers & Windows
Move indices instead of re-scanning — the sliding window.
BFS / DFS
Explore in rings or dive deep — every graph and tree traversal.
Dynamic Programming
Cache overlapping subproblems — edit distance, shortest paths.
Greedy
Take the locally best choice — Kruskal’s MST, Dijkstra.
Backtracking
Try, recurse, undo — N-Queens and constraint search.
Complexity reference
The Big-O you'll be asked to recite — data-structure operations and the sorting algorithms compared. The full version lives on the Big-O cheatsheet.
Data structure operations · average case
| Structure | Access | Search | Insert | Delete |
|---|---|---|---|---|
| Array | O(1) | O(n) | O(n) | O(n) |
| Dynamic Array | O(1) | O(n) | O(1)* | O(n) |
| Hash Table | — | O(1) | O(1) | O(1) |
| Linked List | O(n) | O(n) | O(1) | O(1) |
| Stack / Queue | O(n) | O(n) | O(1) | O(1) |
| Binary Search Tree | O(log n) | O(log n) | O(log n) | O(log n) |
| Heap | O(1)† | O(n) | O(log n) | O(log n) |
* amortized · † peek the max/min
Sorting algorithms
| Algorithm | Best | Average | Worst | Space | Stable |
|---|---|---|---|---|---|
| Quicksort | O(n log n) | O(n log n) | O(n²) | O(log n) | No |
| Merge Sort | O(n log n) | O(n log n) | O(n log n) | O(n) | Yes |
| Heap Sort | O(n log n) | O(n log n) | O(n log n) | O(1) | No |
| Counting Sort | O(n + k) | O(n + k) | O(n + k) | O(k) | Yes |
Learn it. Practice it. Keep it.
Data structures & algorithms — frequently asked questions
What is the best way to learn algorithms and data structures?
Build intuition before memorizing. Watching an animation or grinding LeetCode templates rarely sticks because it's passive — you remember what you've done, not what you've watched. Each lesson here is a playable game: you solve the problem yourself and fail, then see exactly why the algorithm wins, followed by the formal pseudocode, time and space complexity, a worked trace and a quiz. Feeling the problem first, then formalizing it, is what makes data structures and algorithms stick for interviews and real work.
Do these algorithm lessons help with coding interviews?
Yes. Data structures and algorithms (DSA) are half of every technical interview loop — system design is the other half, covered separately on the site. The lessons target the graph, shortest-path, sorting, search and dynamic-programming topics that come up most often, and they build the reasoning behind each algorithm so you can adapt under pressure instead of recalling a memorized template.
Which algorithm should I learn first?
Start with Dijkstra's shortest-path algorithm (The Last Mile). Graphs and shortest paths underpin pathfinding, network routing and a large share of interview questions, and the priority-queue idea at Dijkstra's core carries straight over to BFS, A*, and Prim's algorithm. From there, branch into sorting, binary search and dynamic programming as they're added.
Do I need to be good at math to learn algorithms?
No. These lessons lead with visual intuition and a concrete story, not proofs. You'll meet Big-O notation and see why each algorithm is correct, but the understanding comes from playing the problem — driving it, predicting its moves, and breaking it — not from heavy mathematics.
How is this different from a textbook, a video, or LeetCode?
You participate instead of watching. A textbook explains and a video shows; here you drive the algorithm, predict its next step, and even sabotage it to see where it breaks. That active recall, paired with the full theory (pseudocode, complexity, a worked trace and a quiz), builds far more durable understanding than passively reading or grinding problems before the concept has clicked.
Are the algorithm lessons free?
Yes — every lesson is completely free, runs entirely in your browser with no account or sign-up, and is keyboard-playable with a text version of each diagram for screen readers.