Algorithm Roadmap
Your interactive journey to algorithm mastery
Enable JavaScript for interactive progress. You can read every topic and follow its prerequisites below.
The spectrum shows cumulative learning depth. Company and role examples are illustrative, not an employer ranking or a job-readiness guarantee. Each topic lists its prerequisites. Explore any specialist branch that catches your interest.
01 — Fundamentals
Startups · early-career roles
Build a base with sequences, pointers, hashing and sorting. Start here for early-career preparation, and keep using these foundations at every company and later stage.
Arrays, Strings & Pointer Scans
- Big-O Growth & RAM Memory Layout — Byte addressing, CPU cache lines, worst-case vs amortized cost, and space complexity.
- Static Array — Values at contiguous integer positions with O(1) indexed access and O(n) shift insertions.
- Dynamic Array — Logical length vs allocated capacity, geometric doubling, and O(1) amortized append.
- String & Character Sequences — Code units, immutable vs mutable buffers, slicing bounds, and palindrome scans.
- Matrix & 2-D Grid — Row-major addressing, 4-way and 8-way cell neighborhoods, and in-place boundary traversal.
- Two Pointers — Converging opposite-end and read/write pointer invariants in O(1) extra space.
- Three Pointers & Dutch Flag — Fixed anchor + moving pair and three-way low/mid/high partitioning on one array.
- Sliding Window — Fixed and elastic contiguous `[l, r]` windows with O(1) incremental boundary updates.
- Prefix-Sum Array — Leading-zero cumulative row turning arbitrary `[start, stop)` range sums into `P[stop] - P[start]`.
- Difference Array — Apply batched `[l, r)` range additions via two O(1) boundary deltas before a single prefix pass.
- 2-D Prefix (Summed-Area) Table — Padded integral matrix answering arbitrary sub-rectangle sums with four corner reads.
Linked Lists, Stacks & Queues
- Singly Linked List — Heap-allocated nodes wired by `next` links, dummy heads, and in-place pointer reversal.
- Doubly Linked List — Symmetric `prev` and `next` pointers with LEFT/RIGHT sentinels for O(1) arbitrary node splice.
- Circular Linked List — Tail-to-head wraparound for round-robin rings and cyclic traversal invariants.
- Fast & Slow Pointers (Floyd’s Tortoise & Hare) — Two-speed pointer walks for exact midpoint discovery and O(1)-space cycle entry proof.
- Random-Pointer & Multilevel Linked Lists — Interleaved deep-copying of cross-linked nodes and DFS flattening of nested child chains.
- Stack (LIFO) — Last-in, first-out top discipline powering nested bracket matching, undo history, and DFS.
- Min Stack — Paired value and depth-minimum stacks preserving O(1) minimum queries across pops.
- Monotonic Stack — Evict dominated indices on push to find next greater/smaller boundaries in one linear scan.
- Queue (FIFO) — First-in, first-out arrival/removal discipline for fair scheduling and level-by-layer BFS.
- Queue from Two Stacks — Lazy IN-to-OUT stack reversal achieving amortized O(1) FIFO operations.
- Ring Buffer (Circular Queue) — Fixed-capacity array with modular read/write cursors and zero memory allocations.
- Deque (Double-Ended Queue) — Symmetric O(1) push and pop at both front and back ends.
- Monotonic Deque — Expire out-of-window indices at the front and pop dominated candidates at the back for O(n) sliding maxima.
Bitsets, Hashing, Maps & Sets
- Bitset & Bitwise Operations — Word-level XOR/AND/OR shifts, `x & (x - 1)` lowest-set-bit tricks, and packed bitsets.
- Direct-Address Table & Frequency Array — Map bounded integer/ASCII domains straight to array slots without hashing overhead.
- Hash Functions & Hash Tables — Deterministic hashing, separate chaining vs open addressing, tombstones, and load-factor resizing.
- Hash Map (Dictionary) — Unordered key-to-value associations powering complement lookups, grouping, and memoization.
- Hash Set — Unique-key membership, O(1) duplicate filtering, and visited-state tracking.
- Frequency Map / Counter — Key-to-multiplicity maps handling zero-crossings for anagrams, windows, and subarray counts.
- Bucket Array — Group items by bounded integer counts or attributes to avoid O(n log n) sorting.
- Multiset (Bag) — Multiplicity-aware sets supporting single-copy vs all-copy erasure.
- Multimap — One-to-many key-to-collection mappings for inverted indexes and grouped records.
- Insertion-Ordered (Linked) Hash Map — Coordinate a hash index with a doubly-linked chain for deterministic iteration and `move_to_end`.
- Randomized Set (`O(1)` Insert, Delete & Sample) — Pair a dense array with a value-to-index map using swap-with-last deletion for uniform `getRandom`.
- Randomized Collection with Duplicates — Dense array + value-to-index-set map preserving frequency-weighted sampling under swap-delete.
- Cuckoo Hashing — Give each key alternative buckets and relocate occupants when an insertion finds its first choice full.
Recursion, Call Stack & Divide-and-Conquer
Sorting Algorithms
- Bubble Sort & Early-Exit Optimization — Compare neighbouring numbers, swap them when needed, and stop when a whole pass makes no swaps.
- Selection Sort — Find the smallest remaining value, then swap it into the next unfinished position.
- Insertion Sort (Iterative & Recursive) — Hold the next value, shift larger neighbours right, and insert it into the ordered part.
- Gnome Sort — Insertion Sort expressed with a single cursor that steps forward when ordered and swaps backward when out of order.
- Merge Sort — Sort two smaller lists, then compare their next values to merge them in order.
- Heap Sort — Build a max-heap in O(n) in-place, then repeatedly swap the root maximum to the shrinking tail in O(n log n).
- Quick Sort & Quickselect — Choose a pivot, follow the swaps, and sort the smaller pieces. Use the same partition to find one rank.
- Timsort: Runs & Stable Merging — Find existing ordered runs, extend short ones and merge them. Understand Python’s Powersort distinction.
- Counting Sort — Count small-range integer keys, find each group’s places, and keep equal records in their original order.
- Radix & Bucket Sort — Sort by one digit at a time without losing earlier order, then compare with range-based Bucket Sort.
02 — Core techniques
Product teams · Atlassian, Shopify
Atlassian and Shopify illustrate product-engineering targets. Build on your fundamentals with search, trees, heaps, graphs and greedy reasoning, and practice applying them.
Binary Search, Sweep Line & Intervals
Trees, BSTs & Balanced Search Trees
Heaps, Priority Queues & Streams
Graphs, Traversal & Union-Find
- Graph Models: Undirected, Directed & Weighted — Vertices, directed vs undirected arcs, weights, self-loops, parallel edges, and degree invariants.
- Adjacency List — Per-vertex neighbor lists storing sparse graphs in O(V + E) space for fast outgoing iteration.
- Adjacency Matrix & Edge List — Dense O(V²) constant-time edge tables (`∅` vs `0` weight) and flat `(u, v, w)` triples for edge sorting.
- Implicit Grid Graph — Treat 2-D matrix cells as vertices and 4-way rules + wall checks as on-the-fly edges.
- Breadth-First Search (BFS) & Multi-Source BFS — FIFO frontier layers discovering unweighted shortest paths; mark visited on enqueue to prevent duplicates.
- Depth-First Search (DFS) & 3-Color Cycle Detection — Explore branches to completion, track `visiting` vs `visited` states, and classify back-edges.
- Directed Acyclic Graphs (DAGs) & Topological Sort — Kahn’s in-degree queue and postorder DFS ordering dependencies and detecting blocking cycles.
- Disjoint Set / Union-Find (DSU) — Parent-pointer forests with path compression and union by rank/size for near-O(1) connectivity.
- Weighted Disjoint Set — Store relative potentials/ratios on parent links to answer equation and parity constraints.
- Rollback Disjoint Set — Union by rank without destructive path compression + change-log stack for reversible snapshots.
- Minimum Spanning Trees (Kruskal & Prim) — Connect all vertices at minimum edge weight via sorted Edge List + DSU (Kruskal) or Min-Heap cut (Prim).
- Tarjan’s SCCs, Bridges & Articulation Points — Discovery timestamps and `low`-link values exposing strongly connected components and single points of failure.
Caching, Eviction & Stampedes
- Cache Hits, Misses & FIFO Eviction — Temporal/spatial locality, hit ratio math, write-through vs write-back, and First-In First-Out eviction.
- LRU Cache & Eviction Policies — Pair a hash map with a sentinel doubly-linked list for O(1) hits, updates, and least-recent eviction.
- LFU Cache & TinyLFU Admission — Frequency-bucketed doubly linked lists with `min_freq` tracking and recency tie-breaking in O(1).
- Cache Invalidation, TTL & Stale-While-Revalidate — Active vs lazy expiration, cache-aside races, versioned keys, and keeping cached reads fresh.
- Cache Stampede & Singleflight Coalescing — Why one expired hot key triggers 1,000 database queries — and how request coalescing & jittered TTL stop it.
Greedy Algorithms & Essential Math
03 — Advanced techniques
Big tech · Google, Meta, Amazon
Prepare cumulatively across 01–03 for big-tech coding interviews. Choose the advanced techniques relevant to your target role, and practice problem solving, tradeoffs, complexity and testing throughout.
Shortest Paths & Heuristic Search
Backtracking & Dynamic Programming
Tries, String Automata & Range Trees
04 — Specialist topics
For the love of algorithms
Pick a question for the fun of figuring it out. How can a small sketch estimate the number of distinct items in a stream? What makes a file compressible?
Probabilistic Filters & Sketches
- Bloom Filters — Use hashed bit probes to prove absence; inserted items remain present when bits are never incorrectly cleared.
- Counting Bloom Filter — Support deletion of known inserted items with counters; prevent overflow and never delete uncertain members.
- Cuckoo Filter — Store fingerprints in alternative buckets; delete only known inserted items and handle insertion failure near capacity.
- Count-Min Sketch — Estimate item frequencies from rows of hashed counters; nonnegative updates give one-sided overestimation.
- HyperLogLog (Distinct Cardinality) — Estimate distinct counts from leading-zero hash registers; precision controls register count and relative error.
- Quotient Filter — Split a fingerprint into a bucket quotient and stored remainder while preserving runs for lookup and deletion.
- Xor Filter — Build a static membership filter by assigning fingerprints so a small XOR lookup reconstructs each inserted fingerprint.
- Binary Fuse Filter — Arrange the hash graph in segments to build a compact static approximate-membership filter.
- Blocked Bloom Filter — Keep an item's bit probes within a small block to trade cache locality against false-positive behavior.
- MinHash & Jaccard Similarity — Compare sampled minimum hashes to estimate how strongly two sets overlap without retaining every element.
- SimHash & Angular Similarity — Accumulate signed feature votes into a compact signature whose Hamming distance approximates angular similarity.
- Probability, Hashing & Sketch Error — Distinguish hash collisions, bias, one-sided error, variance, and confidence before choosing a sketch and its parameters.
Storage Engines, Vector Search & Distributed CS
- B-Tree (Page-Oriented Multiway Search) — Pack hundreds of keys per 4 KB–16 KB page so billion-row indexes stay 3–4 disk hops tall.
- B+ Tree (Database Clustered & Secondary Indexes) — Separator-only internal nodes + sibling-linked leaf pages powering PostgreSQL/MySQL range scans.
- Write-Ahead Log (WAL) & Crash Recovery — Append-only sequential durability before mutating in-memory pages or memtables.
- LSM Trees, SSTables & Compaction — Combine Skip-List memtables, immutable sorted SSTable runs, k-way heap merge compaction, and Bloom filters.
- Consistent Hashing & Virtual Nodes — Hash servers and keys onto a 2³² ring with virtual nodes so scaling moves only ~1/N keys.
- Rate Limiting: Token Bucket, Leaky Bucket & Sliding Log — Protect distributed APIs from burst overload with O(1) token buckets and sliding-window counters.
- k-d Tree (Multidimensional Splitting) — Cycle coordinate hyperplane splits for low-dimensional nearest-neighbor and orthogonal box search.
- Quadtree & R-Tree (Spatial & Geo Indexes) — Recursive 4-quadrant splits and minimum-bounding-rectangle hierarchies for maps and game worlds.
- Spatial Hash Grid & Geohash — Quantize coordinates into cell buckets or Z-order prefix strings for fast local neighbor queries.
- Vector Indexing: Flat k-NN, IVF, PQ & HNSW — Escape O(N·d) brute-force embedding scans via Voronoi IVF partitions, PQ codebooks, and HNSW graphs.
- Replicated Logs & Raft Leader Consensus — Quorum majorities, randomized election timeouts, and log-matching safety across faulty nodes.
Streaming Statistics & Quantile Sketches
- Streaming Models & Error Guarantees — Distinguish one-pass memory limits, rank error, value error, mergeability, and the meaning of a probabilistic guarantee.
- Count Sketch — Use signed hash counters and median estimates to cancel collision noise in frequency estimates.
- Misra–Gries Frequent Items — Cancel groups of competing items to retain candidates for values that exceed a chosen frequency threshold.
- Space-Saving Heavy Hitters — Replace a least-frequent tracked candidate while preserving an error bound on its estimated count.
- K-Minimum Values Distinct Sketch — Retain the smallest distinct hash values and estimate set cardinality from the sampling threshold.
- Theta Sketch & Set Operations — Use a shared hash threshold to estimate distinct counts while supporting unions, intersections, and set differences.
- Compressed Probabilistic Counting — Encode coupon observations to estimate distinct counts with a compact probabilistic summary.
- KLL Quantile Sketch — Compact weighted sample levels to estimate ranks and quantiles using bounded memory.
- Relative Error Quantiles Sketch — Allocate more rank accuracy toward a chosen distribution tail instead of using a uniform rank-error target.
- t-Digest — Merge ordered weighted centroids with finer resolution near distribution tails for practical percentile estimates.
- DDSketch — Map magnitudes into logarithmic buckets to estimate quantile values with a controlled relative error.
- VarOpt Weighted Sampling — Keep a bounded weighted sample designed for low-variance estimates of subset totals.
Network Flow, Cuts & Matching
Computational Geometry
- Orientation & Robust Geometric Predicates — Use cross-product signs to distinguish left turns, right turns, and collinearity while handling precision deliberately.
- Line Segment Intersection — Combine orientation tests with bounding checks to handle crossings, touching endpoints, and collinear overlap.
- Shoelace Polygon Area — Sum oriented edge contributions around a polygon and preserve the distinction between signed and absolute area.
- Point-in-Polygon Queries — Use ray crossings or winding counts, with an explicit boundary policy, to classify a query point.
- Convex Hull: Monotone Chain — Sort points and remove inward turns while building the lower and upper boundary chains.
- Rotating Calipers — Advance supporting contacts around a convex polygon to find extremal pairs without checking every pair.
- Closest Pair of Points — Split points by coordinate and inspect a bounded neighborhood in the merge strip.
- Sweep-Line Segment Intersections — Maintain an ordered active set and event queue as segment crossings change the sweep order.
- Voronoi Diagrams — Partition the plane by nearest sites and relate cell boundaries to distance comparisons.
- Delaunay Triangulation — Use the empty-circumcircle condition to connect sites and understand its dual relationship with Voronoi cells.
Advanced String Algorithms & Compressed Indexes
Advanced Trees & Offline Queries
Advanced DP, Convolution & Transforms
- Meet-in-the-Middle Search — Split an exponential choice space into two halves and combine their partial results.
- Divide-and-Conquer DP Optimization — Restrict split-point searches recursively when the recurrence has provably monotone optimal choices.
- Knuth Optimization — Narrow interval-DP split searches only after proving the required quadrangle and monotonicity conditions.
- Convex Hull Trick — Rewrite transitions as line evaluations and maintain the lower or upper envelope under the required ordering assumptions.
- Li Chao Segment Tree — Keep the better line at interval midpoints to support line insertion and extremum queries over a bounded domain.
- Polynomial Convolution — Combine coefficient arrays by summing products whose indices contribute to the same output position.
- Fast Fourier Transform — Evaluate coefficient arrays at structured roots of unity and invert the transform to accelerate convolution.
- Number-Theoretic Transform — Perform Fourier-style convolution in a finite field with a suitable modulus and roots of unity.
- Subset Zeta & Möbius Transforms — Aggregate values over submasks and invert the aggregation by processing one bit dimension at a time.
Compression & Information Coding
- Run-Length Encoding — Encode consecutive equal values as runs and recognize when the representation can grow instead of shrink.
- Huffman Prefix Codes — Repeatedly merge the two least frequent symbols or subtrees to build an optimal binary prefix code.
- Arithmetic Coding — Refine a numeric interval according to symbol probabilities and emit enough bits to identify the final interval.
- LZ77 Sliding-Window Compression — Replace repeated text with a backward distance and match length within a sliding dictionary window.
- LZW Dictionary Compression — Grow a phrase dictionary during encoding and reconstruct the same dictionary while decoding codewords.
- Delta & Variable-Length Integer Encoding — Store differences between nearby integer values and use variable-length representations when differences are small.