Quick recap
The key takeaways of every lesson on one page. Read it in ten minutes to refresh the whole track; open a lesson when a point feels unclear.
01 Hashing, two pointers, windows
- Follow one routine: clarify, brute force with its cost, a better plan with cost and invariant, code, test by hand, final complexity.
- Read the constraints first: Python does about simple steps per second, so allows , and needs or .
- Dict and set operations are on average (good hashing) and in the worst case;
x in list,pop(0)and slices are . - Hash map: look up first, then insert; the map holds only earlier elements, so each pair is checked once.
- A subarray sum is a difference of prefix sums, ; counting with a dict that starts at
{0: 1}works with negative numbers in . - Two pointers drop one element per step because the order proves it cannot be in a better answer; fast and slow pointers find the middle of a list and, by Floyd's method, a cycle and its first node with memory.
- A variable sliding window is correct only when the condition is monotone (under shrinking for "longest", under growing for "shortest"); then it is because each index enters once and leaves at most once.
02 Stacks, binary search, heaps
- A stack closes the most recent open item first; with several bracket types a counter is not enough.
- A monotonic stack answers "next greater/smaller element" for all indices in , because each index is pushed once and popped at most once (at most comparisons).
- Binary search needs a monotone predicate (F…F T…T). With ,
while lo < hi,hi = midif elselo = mid + 1, it returns the first True after at most calls. - Binary search on the answer works when " is enough" is monotone; it costs calls of the test.
- A binary heap stores a complete tree in a list (children , ): push and pop cost ,
heapifycosts , and onlyheap[0]is known. - For the largest items of a stream, keep a min-heap of size : time, memory.
- Intervals: sort by start, then one sweep merges them; the fewest meeting rooms equals the largest number of overlapping meetings, found by a sweep over start and end events.
- A greedy algorithm is correct when some optimal solution starts with the greedy choice; for interval scheduling, earliest end first is optimal (exchange argument), while earliest start and shortest first are not.
03 Trees and graphs
- Tree code: solve the left subtree, solve the right subtree, combine at the node; the empty tree is the base case.
- Every traversal costs time. Depth-first traversals need extra space (the current path); level order needs (one level in a queue).
- A binary tree is a BST if and only if its in-order sequence strictly increases. Validate it by passing an open interval down, not by comparing with the parent.
- Pre-order with a null marker for every missing child fixes a tree; an -node tree has markers.
- One loop explores a graph: take a node from the bag, mark it, add its neighbours. A stack gives DFS, a queue gives BFS, a priority queue keyed by distance gives Dijkstra. Cost for BFS and DFS.
- BFS finds the fewest edges from the source in an unweighted graph; mark a node when you put it in the queue.
- Kahn's algorithm outputs all nodes exactly when the graph is a DAG; fewer than means a directed cycle.
- Union-find with union by rank and path compression costs amortized per operation. Dijkstra with a binary heap costs and needs weights ; otherwise use Bellman-Ford () or DAG relaxation.
04 Backtracking and DP
- Backtracking is a depth-first search over partial solutions: choose, explore, undo, and record a copy at each complete solution. Its cost is (number of nodes) × (work per node).
- Pruning cuts subtrees that cannot lead to a solution: 8 queens with one queen per row and attacked squares skipped visits 2,057 nodes instead of boards.
- Use DP when the answer below a node depends only on a small state and states repeat; use backtracking when you must list every solution, because a memo cannot shorten the output.
- The DP script: state, recurrence (cases = every possible last choice), base cases and fill order, answer and cost (number of states × work per state).
- A memo makes a recursion cost for states; a bottom-up table fills the states in topological order, has no recursion limit, and often keeps only one row.
- Edit distance: , proved by case analysis on the last column of an alignment; traceback recovers the edits.
- The tails array of the LIS stays sorted; each new value replaces the first entry it (binary search), so the LIS length costs .
- Greedy coin change fails for coins and amount 6 ( against ); use the DP .
05 Practical multi-part coding
- A practical round is one class that grows over 3–4 parts. Choose state that keeps every operation cheap, write its invariant, and run all old tests after each part.
- Inject the clock and the I/O (
clock=time.monotonic,fetch=...), so tests use a fake clock and fake pages and run fast and deterministically. - Nested transactions: a stack of undo maps holds, per key, the value before the level first touched it.
beginis ;rollbackwrites the top map back;commitcopies a key into the parent only if the parent has no entry for it. - An LRU cache is a dict from key to node plus a doubly linked list in order of use, with sentinels;
getandputare , and each node stores its key for eviction. - A token bucket refills lazily, , and allows a request if ; it allows at most requests in any window of length .
- A fixed-window limiter can allow requests around a window boundary; a sliding log is exact but stores timestamps; a token bucket allows bursts up to and the long-run rate .
- A crawler is a BFS with a seen set: mark a URL as seen when it is discovered. In asyncio, a check-and-add with no
awaitin between needs no lock; with threads it does. - In unfamiliar code: run the tests first, reproduce bugs with a failing test, make the smallest change, and never let a tool edit the tests.
06 ML coding in NumPy
- Softmax does not change when a constant is subtracted from all logits; subtract , so every exponent is and the sum is in .
- ; cross-entropy from logits is , with gradient . Never take of a softmax output.
- Binary cross-entropy from a logit is ; logistic regression has the gradient , a convex loss, and a safe step with .
- On linearly separable data with , logistic regression has no minimizer: gradient descent drives .
- Lloyd's algorithm never increases the inertia and stops after finitely many steps, at a local optimum; use k-means++ seeding, several starts, and vectorized distances clipped at 0.
- , computed in as with average ranks for ties.
- In backprop, every gradient has the shape of its parameter, , and the bias gradient sums over the batch; for softmax cross-entropy with a mean, .
- Check a hand-written gradient with central differences in float64, : a relative error below about means correct.
07 Training loop, AdamW, BPE
- AdamW: decay , then and updates, bias correction , , and the step .
- Bias correction makes unbiased when ; with it, Adam's first step has size in every coordinate, and Adam ignores the scale of the loss.
- L2 inside Adam is divided by , so weights with large gradients are barely regularized; AdamW decays every weight by the same factor .
- Mixed-precision Adam needs about 16 bytes per parameter: 2 (bf16 weights) + 2 (bf16 gradients) + 4 (fp32 master) + 4 () + 4 ().
- Gradient accumulation is exact when each micro-batch loss is divided by (equal sizes); for token losses, divide the summed loss by the total number of tokens in the window.
- fp16 has a small range and needs dynamic loss scaling; bf16 has the fp32 range but only 8 significant bits, so weights, optimizer state and long sums stay in fp32.
- The step order: zero grad, autocast forward, scaled backward, unscale, clip, step, update the scaler, step the schedule.
- Byte-level BPE merges the most frequent adjacent pair (weighted by chunk counts, with a stated tie rule); encoding applies the merges in learned order, and there is no unknown token.
08 Transformer decoder from scratch
- Attention: , masked entries set to before a softmax over the keys, ; scale by the head size because has variance .
- Heads are a reshape:
view(B, T, H, d_h).transpose(1, 2);view(B, H, T, d_h)has the right shape but mixes tokens. Multi-head attention has weights for any . - RMSNorm$(x) = \gamma \odot x/\sqrt{\operatorname{mean}(x^2) + \varepsilon}$: LayerNorm without centering and without ; use the biased mean, inside the root, fp32 inside.
- RoPE rotates pair of and by ; since , the score depends only on the offset . Rotate and , never .
- In a causal decoder, the keys and values of a token never change, so cached decoding equals the full forward pass; new tokens need absolute positions and the mask
tril(diagonal=P), notis_causal=True. - The KV cache needs bytes per token; GQA divides it by .
- Top-p keeps the smallest set of tokens with mass at least (keep sorted token when the mass before it is ), then renormalizes; temperature is applied first.
- Beam search keeps the best prefixes by summed log-probability; finished hypotheses are compared by , because raw scores favour short outputs.
09 Classic ML and A/B tests
- Bias–variance (squared loss): expected test error ; the cross terms vanish because the noise has mean 0 and is independent of the training set.
- L1 (lasso) gives exact zeros by soft thresholding, ; L2 (ridge) only shrinks. L1 = Laplace prior, L2 = Gaussian prior.
- The variance of an average of models with correlation is : bagging lowers variance, random forests also lower ; boosting fits pseudo-residuals and mainly lowers bias.
- ROC-AUC measures ranking and ignores the class ratio; precision and AP depend on it. With rare positives, report precision at the operating point.
- With calibrated probabilities, flag when .
- Bayes with a base rate: 99% sensitivity and specificity at 0.5% prevalence give .
- Sample size per arm: ; half the MDE needs four times the users.
- A/B pitfalls: peeking (10 looks give about 19% false positives), sample-ratio mismatch (check with ), many metrics, interference, unit of analysis ≠ unit of randomization.
10 Deep learning breadth
- Deep networks multiply per-layer gains; initialization, normalization, residual connections, clipping, warmup and Adam all keep these gains near 1 or survive when they are not.
- Variance propagation: , and ReLU halves the second moment, so He initialization uses ; with , 12 ReLU layers shrink it to .
- AdamW decays every weight by outside the adaptive step; L2 inside Adam is divided by and barely regularizes weights with large gradients.
- BatchNorm uses batch statistics in training and running averages in eval; LayerNorm and RMSNorm compute the same function in both and do not depend on the batch, so transformers use them.
- A residual block has Jacobian , so the gradient always has an identity path; pre-LN keeps that path clean and trains stably without warmup.
- Inductive bias: CNNs assume locality and translation equivariance; transformers let all pairs interact at cost and need positional information and more data.
- Flow matching learns the conditional mean velocity ; one Euler step from noise gives the data mean, and with Gaussian paths diffusion and flow matching are one family.
- Before a long run: the first loss should be about , and the model must be able to overfit one batch.
11 LLM breadth
- Training a chat model: pretraining (knowledge) → mid-training (quality, long context) → SFT (format) → preference tuning (which answer people prefer) → RL with verifiable rewards (reasoning), with evaluation at every step.
- A uniform model over tokens has loss and perplexity . Compare perplexity only with the same tokenizer; bits per byte does not depend on it.
- Training compute is FLOPs (2 forward + 4 backward per parameter per token); inference is about FLOPs per token; mixed-precision Adam stores about 16 bytes per parameter.
- Chinchilla: at fixed compute, grow and together, about 20 tokens per parameter, so . The iso-FLOP curve is flat near its minimum, so practice trains smaller models on many more tokens to save inference cost.
- LoRA trains with parameters, random and at the start. It saves gradients and optimizer states, not activations.
- The KL-regularized RLHF objective has the optimal policy . DPO puts this into the Bradley–Terry model, where cancels, and trains offline on pairs.
- GRPO uses the group-normalized advantage instead of a value model; a group with equal rewards gives no signal.
- An accuracy on questions has standard error ; pass@ needs the unbiased estimator .
12 Training at scale
- Mixed-precision AdamW needs 16 bytes per parameter (2 weight + 2 gradient + 12 optimizer states), plus activations of about bytes per layer, or with FlashAttention.
- A ring all-reduce sends bytes per GPU, whatever the number of GPUs; it is a reduce-scatter followed by an all-gather.
- Data parallelism with equal shards gives exactly the full-batch gradient; the all-reduce hides behind the backward pass when each GPU has at least tokens per step.
- ZeRO-1/2/3 shard optimizer states, then gradients, then parameters: ZeRO-3 needs bytes per GPU and sends values per step, DDP.
- Tensor parallelism splits each weight matrix (columns, then rows) and needs 4 all-reduces per layer per step, so it stays inside an NVLink node.
- A pipeline with stages and micro-batches idles a fraction of the step; 1F1B keeps the bubble but caps the stored activations at micro-batches.
- Training costs FLOPs per token (full attention); GPU-hours follow from the total FLOPs at an assumed MFU of 35–45%.
- A job on GPUs fails every on average; the best checkpoint interval is , with overhead .
13 LLM serving
- Decode reads all weights and every sequence's KV cache in each step, so its step time is about : it is memory-bound, and TPOT this step time.
- The KV cache needs bytes per token (800 KiB for Llama-2-13B in bf16); the tokens that fit are the free memory divided by .
- A weight matmul on tokens does about FLOPs per byte, so prefill is compute-bound and decode needs a large batch; decode attention stays at FLOPs per byte for any batch.
- Continuous batching refills a batch slot at the next step after a request ends, which removes idle slots and head-of-line blocking.
- Paged attention stores the cache in fixed blocks with a block table, so each sequence wastes less than one block; reference counts and copy-on-write let sequences share a prefix.
- Weight-only int4/int8 speeds up memory-bound decode; W8A8/FP8 speeds up compute-bound prefill and large batches; an fp8 KV cache doubles the tokens that fit.
- Speculative decoding gives tokens per target pass and keeps the target distribution exactly.
- Little's law turns traffic into concurrency; an M/M/1 server has , so latency explodes near full utilization.
14 ML system design
- An ML system design answer follows a time plan: clarify (0–5 min), metrics (5–8), funnel and numbers (8–11), data and labels (11–19), model (19–27), serving and evaluation (27–34), monitoring, deep dives and trade-offs (34–45).
- Large catalogs need a funnel: retrieval optimizes recall over millions of items cheaply; ranking optimizes precision at the top on a few hundred candidates with rich features; re-ranking adds diversity and rules.
- Back-of-envelope: peak QPS ; index memory ; ranker compute QPS FLOP/s.
- with ; say which gain you use.
- A two-tower model scores , so item vectors go in an ANN index; its in-batch softmax needs the log-Q correction , or popular items are under-scored.
- Ranking learns from impressions with several heads (click, watch time, like, dismiss); weighted logistic regression with watch-time weights learns odds .
- Position bias: weight clicks by (IPS) or use the position as a training-only feature; fight feedback loops with exploration.
- Deploy through a gate, shadow, canary and A/B test, with a fast rollback. PSI has a noise floor with no drift.
15 GenAI system design
- The adaptation ladder: prompting for format and simple tasks, RAG for knowledge that changes or needs citations and access control, fine-tuning for behaviour; RAG for knowledge, fine-tuning for behaviour.
- A RAG system has an offline path (parse, chunk, embed, index with metadata) and an online path (rewrite, hybrid retrieval, fusion, rerank, prompt with chunk ids, generate, check, stream).
- Chunks of tokens with overlap : ; every span of at most tokens lies inside one chunk.
- Hybrid retrieval fuses BM25 and dense lists by ranks: ; a cross-encoder reranks the top 20–100.
- RAG latency is dominated by prefill ( FLOPs) and the extra model calls; prefix caching saves the prefill of the system prompt and the earlier turns.
- An agent with per-step accuracy completes steps with probability (); defend against prompt injection with least privilege and human confirmation.
- Classifier-free guidance: , two denoiser evaluations per step; the number of steps is the main cost lever.
- Evaluate retrieval (recall@k, MRR, nDCG) separately from answers (correctness, faithfulness, citations); check an LLM judge with Cohen's ; compare two systems with a paired test such as McNemar's.
16 Behavioral and research talk
- Behavioral questions collect evidence of past decisions; the level of the offer follows the scope of your stories (your work, the team, several teams).
- STAR plus Reflection: Situation and Task about 25% of the time, Action about 50–55%, Result about 15%, Reflection 5–10%; a 2.5-minute answer is about 375 words at 150 words per minute.
- A strong story says "I" for decisions, has a number in the Situation and in the Result, and contains a decision between real alternatives.
- The six common themes are conflict, failure, ambiguity, influence without authority, ownership and hard trade-off; a bank of 8–10 stories should give each theme at least two stories, with no story used for more than three themes.
- A research talk is judged on depth, judgment, communication and fit; state the main result in the first 3 minutes, then earn it.
- The 5-minute talk keeps the problem and the main result, one picture of the idea, one result with its baseline, and why it matters for the team.
- A decision table (choice, alternatives, evidence, cost or risk, what would change my mind) prepares you to defend every design choice.
- Answer questions with a routine: listen, clarify, answer first in one sentence, give the evidence, say what you do not know and how you would check it.