Explore how an algorithm chooses a path, learns a boundary, or compresses a dataset. Inspect the mathematics, computational costs, assumptions, and implementations in this repository.
Prerequisite: loops, arrays, and functions. Start here before comparing algorithms. Big O is an asymptotic upper bound; Θ is a tight bound and Ω is a lower bound. State the input size and case before making a claim.
Counted toy operations, not milliseconds or benchmark predictions
Example
Growth
n
2n
Auxiliary memory
Derive the bound
Define the dimensions: n elements; V vertices and E edges; n rows and d features.
Count a representative operation, such as one comparison or one pair visit.
Add sequential phases: O(n) + O(n²) becomes O(n²). Multiply independent nested loops: n × m becomes O(nm).
A loop that halves its search interval takes O(log n) iterations. Two pointers each moving forward at most n times still take O(n), even with a nested while loop.
Drop fixed constants and lower-order terms asymptotically: 3n + 5 is Θ(n). Constants and cache behavior still matter in practice.
Time cases, amortization, and memory
Linear search has Θ(1) best-case and Θ(n) worst-case comparisons. Average-case needs an input distribution. Hash lookup is commonly expected O(1), not an unconditional worst-case promise. Dynamic-array append is amortized O(1) across a sequence, although a resizing append can take O(n).
Auxiliary space is extra working memory, excluding the input and, when explicitly stated, the returned output. Total memory includes input, working memory, and output. Recursive depth consumes stack space: balanced tree DFS uses O(log n) stack; a chain can use O(n). Enumerating every subset requires Θ(n·2ⁿ) output elements even if the recursion path needs only O(n).
These guides save snapshots. Copying an n-cell board for O(n) frames can consume O(n²) time and memory even when the underlying algorithm uses O(1) auxiliary space. Input validation and trace construction are separate from the algorithm's displayed bound. Teaching integer arithmetic assumes bounded values; very large integers have nonconstant arithmetic costs.
Worked comparisons
Pair sum: brute-force pairs take Θ(n²); sorting then two pointers takes O(n log n) overall; already-sorted two pointers take O(n). State whether sorting is included.
Graph traversal: O(V + E) with adjacency lists; repeatedly scanning an adjacency matrix takes O(V²). Representation changes cost.
Model training: one dense gradient pass takes O(nd). I iterations take O(Ind); K-fold evaluation multiplies fitting work by K.
Heap selection: O(n log(k + 1)) time and O(k) working memory. A small k and a large n are different dimensions.
02 / DECISIONS IN A FRONTIER
The shortest route depends on what you minimize.
Two edges can cost more than three. Step through the same weighted, directed graph with five strategies.
Intermediate · 15 minutes · Prerequisites: Big O, graphs, queues, and heaps. Try the contrasting graph presets before reading the completed results.
CurrentExpandedQueuedUnseen
Edge labels are costs. Heuristics: h(S)=3, h(A)=2, h(B)=0, h(C)=1, h(G)=0. The default values are admissible for this graph. DFS follows A before B. Frontier entries are queued candidates; stale entries can await removal.
Completed results on the selected illustrative graph
Method
Priority
Route
Cost
Guarantee here
03 / WATCH AN UPDATE
Learning is an iterative process.
Vary a step size, inspect a projection, and connect the geometry to the formula.
Gradient descent
One standardized feature, five noiseless points, and mean squared error. Move the step slider to inspect an update.
PCA: preserve a direction
Project a cloud onto its principal axis. Gray segments show discarded perpendicular variation. This geometric illustration is not a fitted dataset benchmark. The principal axis runs diagonally through the centered cloud; projecting onto it discards each point’s perpendicular displacement. Reconstruction returns a point on that axis, losing the discarded variation.
scores = X_centered V_k reconstruction = scores V_kᵀ + mean
Fit scaling and PCA on training rows. Variance retained is not classification accuracy. For an executed example, open Visual foundations.
04 / THE TECHNICAL REFERENCE
Choose a method. Understand its trade-offs.
Read the objective before the implementation. Each entry links to project code and states where its guarantees end.
Follow one branch deeply before backtracking, using a stack or recursion.
priority = most recently queued candidate
Walk through the algorithm
Push the start.
Expand the next unvisited state.
Push neighbors in reverse input order to visit the first neighbor first.
Computational cost
Conventional traversal: O(V + E) time and O(V) bookkeeping. Recursive implementations can reach Python’s recursion limit.
Assumptions & failure modes
Does not guarantee fewest edges or minimum cost. The visual trace marks nodes visited on expansion, allowing a deeper route to a node already queued elsewhere.
Example. With A before B, the diagram follows S → A → C → G, cost 3. This depends on neighbor order.
Follow the heuristic estimate that appears closest to the goal, ignoring the cost already paid.
f(n) = h(n)
Walk through the algorithm
Order a heap by heuristic estimate.
Expand the lowest-estimate state.
Discover neighbors once and queue them by their estimates.
Computational cost
For the finite discovered-once implementation, up to O((V + E) log V) with a heap, plus copied path storage. A heuristic does not guarantee a small search.
Assumptions & failure modes
Not an optimal-path algorithm. Even an admissible heuristic does not make greedy search optimal because g(n) is omitted.
Example. h(B)=0 and h(A)=2, so the diagram takes the expensive B route.
Balance cost already paid against an estimate of remaining cost.
f(n) = g(n) + h(n)
Walk through the algorithm
Order candidates by g + h.
Track best known g and remove stale candidates.
Reopen improved states; return when the goal is popped.
Computational cost
Heuristic-dependent. Consistent heuristics avoid re-expansion in the usual implementation; inconsistent heuristics can require reopening. Search can still grow exponentially in depth.
Assumptions & failure modes
For these finite nonnegative graphs, the heuristic must be admissible, zero at the goal, and improved states reopened when needed. With h=0, A* becomes UCS.
Example. The supplied admissible heuristic finds cost 3, even though B initially looks closer.
Predict a numeric target from an intercept and weighted features.
ŷ = b + xᵀw; L = (1/n) Σᵢ(ŷᵢ − yᵢ)²
Walk through the algorithm
Reserve held-out observations.
Fit coefficients by least squares or gradient descent.
Compare held-out errors with a baseline.
Computational cost
A full dense gradient step costs O(nd). Dense least squares is solver-dependent; a common tall-matrix QR approach is O(nd²).
Assumptions & failure modes
Linear responses can underfit nonlinear relationships. Correlated features can destabilize coefficients. The NumPy model learns scaling on training rows only.
Example. Points (0,1), (1,3), (2,5) fit y = 1 + 2x. See the salary notebook for a dataset application.
Convert learned class scores into probabilities with sigmoid or multiclass softmax.
p(y=1|x) = 1 / (1 + exp(−(b + xᵀw)))
Walk through the algorithm
Fit preprocessing within the training pipeline.
Minimize regularized cross-entropy.
Choose C or thresholds on validation data and report final test metrics.
Computational cost
Solver-dependent. A dense gradient pass costs O(nd) for binary classification or O(ndc) for c classes. Iteration count depends on convergence.
Assumptions & failure modes
This is a classifier despite its name. Linear scores can underfit nonlinear structure. In scikit-learn, larger C means weaker regularization. Probability calibration is not guaranteed.
Example. At score z=0, p=0.5. With y=1, cross-entropy is −log(0.5), approximately 0.693.
Classify a query using nearby training examples and a vote.
d²(x,z) = Σⱼ(xⱼ − zⱼ)²; prediction = majority among k nearest
Walk through the algorithm
Learn feature scaling on training observations.
Compute distances from a query to training rows.
Select k neighbors and apply the documented tie rule.
Computational cost
The NumPy query uses O(nd) distance work plus O(n log n) sorting. Indexed implementations have data- and dimension-dependent costs.
Assumptions & failure modes
Feature units matter. Small k can follow noise; large k smooths boundaries. The NumPy version breaks distance ties by training order and vote ties by sorted class order.
Example. For [0,1,3] with labels [A,A,B], query 2.2 predicts B at k=1 but A at k=3.
Repeat until a depth, leaf-size, or purity stopping rule.
Computational cost
Training depends on split search and shape; O(d n log n) is a common balanced-tree description. Prediction is O(depth), potentially O(n) for a degenerate tree.
Assumptions & failure modes
Deep trees can memorize noise. Training impurity improvements do not guarantee generalization. Select depth using training-only CV.
Example. Two positives and two negatives have Gini 0.5. Two pure children have weighted impurity 0.
Balance a separating margin against penalties for classification violations. Kernels enable nonlinear boundaries.
hinge = max(0, 1 − y f(x)); RBF K(x,z) = exp(−γ‖x−z‖²)
Walk through the algorithm
Fit feature scaling within training data.
Fit the margin-based classifier with chosen C and kernel parameters.
Validate C and gamma without using final test rows.
Computational cost
Kernel training commonly needs at least quadratic resources and can approach cubic time in n, depending on data/solver. Kernel storage can be O(n²). Prediction depends on support-vector count.
Assumptions & failure modes
Distances depend on scaling. Large C or gamma can overfit. Decision scores are not automatically calibrated probabilities.
Example. The project uses StandardScaler followed by an RBF SVC for Iris.
Combine class priors and Gaussian feature likelihoods under conditional independence.
score(y) = log P(y) + Σⱼlog N(xⱼ; μᵧⱼ, σ²ᵧⱼ)
Walk through the algorithm
Estimate class priors.
Estimate feature means and variances per class.
Sum log-likelihoods and priors; choose the largest posterior score.
Computational cost
Training is O(nd), with O(cd) stored parameters. A query typically costs O(cd).
Assumptions & failure modes
Correlated features can double-count evidence. Gaussian assumptions can fit poorly. Variance smoothing improves numerical behavior, not assumption validity.
Example. GaussianNB uses the same Iris partition as the tree, forest, and SVM.
Alternate nearest-center assignments and mean updates to find compact groups.
J = Σᵢ ‖xᵢ − μ_label(i)‖²
Walk through the algorithm
Initialize k centers for several seeded starts.
Assign each point to its nearest center.
Update nonempty centers to member means; retain the run with lowest inertia.
Computational cost
Basic Lloyd updates cost O(I n k d) per start. The NumPy implementation materializes pairwise differences and can require O(nkd) temporary memory.
Assumptions & failure modes
IDs are arbitrary. Starts can find different local minima. Compact similar-scale groups fit better than elongated or unequal-density groups. Empty centers are retained here.
Example. Assign [0,2,8,10] to [0,10]; the next centers become [1,9].
Project centered features onto orthogonal directions retaining maximum training variance.
X_centered = UΣVᵀ; scores = X_centered V_k
Walk through the algorithm
Fit scaling and centering on training rows.
Find principal directions using SVD or an eigensolver.
Transform unseen observations without refitting; optionally reconstruct.
Computational cost
Dense full SVD is typically O(min(nd², n²d)); truncated/randomized solvers can be cheaper. Projection into k components costs O(ndk).
Assumptions & failure modes
Largest variance does not imply predictive relevance. Units and outliers can dominate. Component signs are arbitrary; inspect reconstruction or subspaces.
Example. A cloud near y=x has a diagonal first direction. One-component reconstruction removes perpendicular variation.
Combine linear layers and nonlinear activations to learn feature interactions.
h = ReLU(W₁x+b₁); scores = W₂h+b₂; cross-entropy + regularization
Walk through the algorithm
Initialize weights and define the objective.
Use backpropagation to obtain derivatives and optimize weights.
Evaluate with the same fitted input representation on held-out rows.
Computational cost
Forward/backward work is proportional to batch size times layer connections. Total cost depends on iterations/optimizer; L-BFGS also stores optimization history.
Assumptions & failure modes
More units do not guarantee better performance. Weak regularization, small datasets, or repeated test-based tuning can overfit. Seeds affect results.
Example. The NLP helper uses a 32-unit ReLU hidden layer, L2 regularization, and L-BFGS on TF-IDF.
Fit the vocabulary and document frequencies using training texts only.
Create sparse weighted document vectors.
Transform held-out text using fixed vocabulary and IDF.
Computational cost
Roughly proportional to token occurrences plus vocabulary processing. Sparse storage follows nonzero entries, not all document×vocabulary combinations.
Assumptions & failure modes
TF transformation and normalization are configurable. The NLP helper uses sublinear TF, smoothed IDF, and default L2 normalization. New words never create new columns at prediction time.
Example. A term appearing only in test articles is not added to the training vocabulary.
Compare a finite parameter grid using training-only CV, then refit the selected pipeline.
λ* = argmax_λ mean CV score(λ)
Walk through the algorithm
Predefine the grid and scoring metric.
Cross-validate the complete pipeline for each configuration.
Refit on all training rows; evaluate final test data after selection.
Computational cost
H configurations and K folds need approximately H×K fits, plus final refitting.
Assumptions & failure modes
The best CV score is selection-biased, not a final unbiased test estimate. Extensive comparisons may require nested CV or fresh outer evaluation.
Example. The project compares C ∈ {0.01,0.1,1,10} by average precision, then reports held-out metrics.
No methods match that search.
Choose a threshold. Inspect the tradeoff.
Illustrative validation scores for eight cases, not a trained model benchmark. Positive prediction means score ≥ threshold.
Choose an operating threshold using validation data and error costs. Freeze it before reporting held-out test performance. Precision or recall is undefined when its denominator is zero.
05 / TRUST THE PROCESS
A good score starts with a valid experiment.
Model selection belongs inside training data. The final test set is a report after selection, not another tuning tool.
Text equivalent of the pipeline: deduplicate the dataset and split it into training and held-out test partitions. Cross-validate the entire preprocessing-and-model pipeline using only training rows. Select settings, refit on all training rows, then evaluate once on the held-out test partition. The test branch bypasses model selection.
Imbalanced classification
With 90 negatives and 10 positives, predicting negative for every row gives 90% accuracy, zero positive recall, and 50% balanced accuracy. Compare against a baseline before celebrating accuracy.
Use per-class metrics, confusion counts, average precision, PR/ROC curves, and validation learning curves. Average precision differs from trapezoidal PR area. Fold standard deviation is not a confidence interval.
Choose thresholds on validation data using error costs. If test-set error inspection guides changes, obtain a fresh test set. Stratification cannot fix duplicate, grouped, or time-dependent observations.
A pipeline prevents preprocessing leakage inside cross-validation. It cannot repair biased labels, an inappropriate split, or a dataset that does not represent future inputs.
Classes; or neighbors, clusters, or components as stated.
V / E
Graph vertices / directed edges.
g(n) / h(n)
Cost paid / estimated remaining path cost.
η / I
Learning rate / optimization iterations.
Training / validation / test
Fit parameters / choose settings / final evaluation.
Complexities describe typical or explicitly stated implementations, not universal runtime guarantees. NumPy teaching models retain history for inspection and omit production optimizations. Browser experiments use illustrative data; they do not run Python models.