FOUNDATIONS

Algorithms & DSA

Data structures and algorithms taught as playable games and runnable challenges — graphs, sorting, search and dynamic programming, the half of every interview loop you can practice.

128 pieces · 7 formats

Handbooks 1

Roadmaps 1

System Designs 1

Paper Breakdowns 1

Algorithm Games 99

Algorithm

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.

GraphsShortest PathPathfinding
Algorithm

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.

SearchingDivide & ConquerArrays
Algorithm

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.

SortingDivide & ConquerRecursion
Algorithm

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.

SortingDivide & ConquerRecursion
Algorithm

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.

GraphsBFSPathfinding
Algorithm

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.

GraphsShortest PathPathfinding
Algorithm

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.

Number TheoryPrimesMath
Algorithm

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.

GraphsDFSTopological Sort
Algorithm

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.

GraphsUnion-FindData Structures
Algorithm

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.

SortingHeapsData Structures
Algorithm

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.

Dynamic ProgrammingStrings
Algorithm

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.

GraphsMinimum Spanning TreeGreedy
Algorithm

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.

GraphsShortest PathDynamic Programming
Algorithm

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.

StringsPattern Matching
Algorithm

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.

StringsTreesData Structures
Algorithm

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.

ArraysTwo Pointers
Algorithm

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.

BacktrackingRecursion
Algorithm

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.

Data StructuresHashing
Algorithm

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.

Data StructuresPointers
Algorithm

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.

Data Structures
Algorithm

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.

Data StructuresTrees
Algorithm

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.

Data StructuresTreesRanges
Algorithm

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.

ArraysTwo Pointers
Algorithm

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.

ArraysPrefix Sums
Algorithm

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.

Dynamic ProgrammingArrays
Algorithm

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.

Dynamic Programming
Algorithm

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.

StringsPattern MatchingHashing
Algorithm

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.

SortingNon-comparison
Algorithm

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.

Dynamic Programming
Algorithm

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.

Dynamic Programming
Algorithm

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.

Data StructuresRanges
Algorithm

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.

GraphsShortest PathDynamic Programming
Algorithm

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.

SearchingDivide & Conquer
Algorithm

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.

SortingDistribution
Algorithm

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.

BacktrackingRecursion
Algorithm

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.

BacktrackingRecursion
Algorithm

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.

BacktrackingConstraints
Algorithm

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.

MathNumber Theory
Algorithm

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.

MathNumber Theory
Algorithm

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.

Dynamic ProgrammingStrings
Algorithm

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.

StringsPattern Matching
Algorithm

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.

Data StructuresHeaps
Algorithm

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.

GraphsMinimum Spanning Tree
Algorithm

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.

Data StructuresTrees
Algorithm

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.

StringsPalindromes
Algorithm

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.

GreedyCompression
Algorithm

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.

GreedyIntervals
Algorithm

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.

StackArrays
Algorithm

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.

Two PointersSorting
Algorithm

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.

ArraysStreaming
Algorithm

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.

SortingDivide & Conquer
Algorithm

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.

ArraysStreaming
Algorithm

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.

SortingArrays
Algorithm

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.

MathDivide & Conquer
Algorithm

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.

Data StructuresLinked Lists
Algorithm

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.

Divide & ConquerBacktracking
Algorithm

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.

TreesDivide & Conquer
Algorithm

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.

Data StructuresHashing
Algorithm

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.

GraphsDepth-First Search
Algorithm

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.

Data StructuresTrees
Algorithm

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.

StringsAutomata
Algorithm

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.

GraphsMax Flow
Algorithm

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.

HashingDistributedData Structures
Algorithm

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.

HashingProbabilisticStreaming
Algorithm

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.

ProbabilisticStreamingHashing
Algorithm

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.

RandomizationArrays
Algorithm

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.

SortingNon-comparisonDistribution
Algorithm

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.

GraphsBFSShortest Path
Algorithm

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.

TreesData Structures
Algorithm

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.

StorageData Structures
Algorithm

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.

GeometryDivide & Conquer
Algorithm

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.

SortingDistribution
Algorithm

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.

GraphsDFS
Algorithm

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.

ProbabilisticHashingStreaming
Algorithm

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.

GeometryIntervalsSorting
Algorithm

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.

Number TheoryMath
Algorithm

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.

Divide & ConquerMath
Algorithm

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.

Dynamic ProgrammingTrees
Algorithm

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.

GraphsDFS
Algorithm

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.

HeuristicsOptimization
Algorithm

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.

Number TheoryMath
Algorithm

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.

Number TheoryMath
Algorithm

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.

Data StructuresRanges
Algorithm

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.

Data StructuresRanges
Algorithm

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.

Dynamic ProgrammingGraphs
Algorithm

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.

Data StructuresTrees
Algorithm

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.

StringsSorting
Algorithm

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.

Dynamic ProgrammingMath
Algorithm

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.

Data StructuresTrees
Algorithm

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.

Data StructuresTrees
Algorithm

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.

RangesData Structures
Algorithm

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.

SortingDivide & Conquer
Algorithm

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.

GraphsMax Flow
Algorithm

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.

GraphsOptimization
Algorithm

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.

Divide & ConquerMath
Algorithm

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.

Data StructuresRanges
Algorithm

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.

Data StructuresTrees
Algorithm

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.

StringsData Structures
Algorithm

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.

Dynamic ProgrammingGreedy

Coding Challenges 24

Challenge

Two Sum

The classic warm-up: find the two numbers that add up to a target. Brute force is O(n²) — a hash map gets you to one pass, O(n). Solve it in Python or TypeScript, right in your browser, with hidden tests and a reveal-solution button.

ArraysHash Map
Challenge

Valid Parentheses

The canonical stack problem: decide whether every bracket is closed by the right type, in the right order. A stack turns nested matching into a single pass. Solve it in Python or TypeScript with hidden tests.

StackStrings
Challenge

Fizz Buzz

The famous screening question. Print 1…n, but multiples of 3 become "Fizz", of 5 become "Buzz", and of both become "FizzBuzz". Easy — the catch is testing divisibility in the right order. Solve it in Python or TypeScript.

MathStringsWarm-up
Challenge

Number of Islands

The canonical connected-components question. Flood-fill each unvisited patch of land with BFS or DFS, count how many floods you started — grid traversal, visited bookkeeping, and the classic diagonal trap. Solve it in Python or TypeScript.

GraphsBFS/DFSInterview Classic
Challenge

Merge Intervals

Calendar apps and memory allocators run on this: sort by start, sweep once, grow or close the current block. Touching endpoints merge, nested intervals vanish — the classic that punishes off-by-one thinking. Solve it in Python or TypeScript.

SortingArraysInterview Classic
Challenge

Top-K Frequent Elements

Count, then rank — the two-step pattern behind trending topics and hot-key detection. A hash map counts; a (-count, value) sort ranks with a clean tie-break; buckets get you to O(n) if you want the flex. Solve it in Python or TypeScript.

Hash MapHeapsInterview Classic
Challenge

3Sum

The rite of passage: every unique zero-sum triplet, no duplicates, no O(n³). Sort once, fix one element, squeeze the rest with two pointers, and skip duplicates at all three levels. Solve it in Python or TypeScript.

Two PointersArraysInterview Classic
Challenge

Union-Find (Connected Components)

The disjoint-set behind Kruskal’s MST and network connectivity: answer "are these connected?" in near-constant time with union by rank and path compression, then count the components. Solve it in Python or TypeScript, with hidden tests.

GraphsDisjoint SetData Structures
Challenge

Min Stack

A stack that also returns its minimum in O(1) — no scanning. Carry the running minimum alongside each element. Replay push/pop/top/getMin operations. Solve it in Python or TypeScript, with hidden tests.

StackData StructuresDesign
Challenge

LFU Cache

The cache that evicts what you use least often — and, on ties, least recently. Harder than LRU: track frequency and recency together, still O(1) per op. Replay get/put operations. Solve it in Python or TypeScript, with hidden tests.

DesignCachingHash Map
Challenge

Implement a Trie

The prefix tree behind autocomplete and spell-check: insert, search, and startsWith in time proportional to word length. Replay the operations on a tree keyed by characters. Solve it in Python or TypeScript, with hidden tests.

TrieStringsDesign
Challenge

KMP Failure Table

The precomputation that makes KMP string search run in O(n): for every prefix, the longest proper prefix that is also a suffix. Get it right and matching never backtracks. Build it in Python or TypeScript, with hidden tests.

StringsPattern MatchingDynamic Programming
Challenge

Longest Common Subsequence

The DP behind "git diff" and DNA alignment: the longest subsequence common to two strings (order kept, gaps allowed). A classic 2-D table in O(m·n). Solve it in Python or TypeScript, with hidden tests.

Dynamic ProgrammingStrings
Challenge

Mini Regex Matcher (. and *)

Implement regex matching with "." and "*" — the classic hard interview problem. The subtlety: "*" can match nothing or many, so you must explore both. Solve it with DP in Python or TypeScript, with hidden tests.

Dynamic ProgrammingStringsRecursion
Challenge

Expression Calculator

Evaluate an arithmetic string with precedence and parentheses, the way an interpreter does. A tiny recursive-descent parser handles precedence naturally. Solve it in Python or TypeScript, with hidden tests.

ParsingRecursionStack
Challenge

JSON Parser (Recursive Descent)

Write the parser behind every API and config file: turn a JSON string into native objects, arrays, numbers, strings, booleans and null — by hand, without the built-in parser. Recursive descent mirrors the grammar. Solve it in Python or TypeScript, with hidden tests.

ParsingRecursionStrings
Challenge

Dijkstra’s Shortest Paths

The algorithm every routing table and map app leans on: single-source shortest paths with non-negative weights. Greedily settle the closest node, relax its edges, repeat. Return the distance to every node. Solve it in Python or TypeScript, with hidden tests.

GraphsShortest PathGreedy
Challenge

A* Pathfinding on a Grid

The pathfinder inside games and robots: A* expands nodes by "cost so far + estimated cost to go", so the heuristic focuses the search toward the goal instead of spreading blindly. Return the shortest path length. Solve it in Python or TypeScript, with hidden tests.

GraphsShortest PathHeuristics
Challenge

Course Schedule (Cycle Detection)

Can you finish every course given its prerequisites? The classic "is this dependency graph acyclic?" check a build system runs. Detect a cycle with a topological sort. Solve it in Python or TypeScript, with hidden tests.

GraphsTopological SortBFS
Challenge

Word Ladder

Transform one word into another one letter at a time, every step a real word — a shortest path in a hidden graph, so a job for BFS. Return the shortest ladder length. Solve it in Python or TypeScript, with hidden tests.

GraphsBFSStrings
Challenge

Matrix Exponentiation

Raise a matrix to the n-th power in O(log n) multiplies instead of n — the trick that computes the billionth Fibonacci number almost instantly. Fast exponentiation, lifted from numbers to matrices. Solve it in Python or TypeScript, with hidden tests.

MathDivide and ConquerLinear Algebra
Challenge

Skip List Insert & Search

O(log n) search and insert from nothing but linked lists and express lanes — the structure behind Redis sorted sets. Here node heights are given, so it’s fully deterministic. Solve it in Python or TypeScript, with hidden tests.

Data StructuresLinked ListSearch
Challenge

Reservoir Sampling

Pick k items uniformly at random from a stream of unknown length — one pass, O(k) memory. Here the random draws are supplied, so the result is deterministic and testable. Solve it in Python or TypeScript, with hidden tests.

SamplingStreamingProbability
Challenge

Repair the Spread Traversal

Inherited code computes how far something spreads through a contact graph, and the answers are wrong in a way that is invisible on small inputs. A one-way adjacency map, a frontier with no dedupe, and a seen-set updated one step too late. Solve it in Python or TypeScript, with hidden tests.

FDEInterviewGraphs

Interactive Tools 1

About algorithms & DSA

Data structures and algorithms are the half of every interview loop you can actually practise — and the mental library you reach for when a problem looks new but isn't. Graphs, sorting, search, dynamic programming: each is a pattern that turns an intractable brute force into something that scales.

Taught here as playable games and runnable challenges, the goal is intuition, not memorisation — you drive the problem, feel why the naive approach fails, then meet the algorithm that fixes it, with a worked trace and code you can run in the browser. Recognising which pattern a problem wants is the skill that transfers to real engineering, not just interviews.

More in Foundations

← Browse all topics