Amazon’s delivery-time estimation team keeps its baseline deliberately boring: a closed-form least-squares fit over package and route features, written in raw NumPy so ops analysts can audit every coefficient without a sklearn dependency. Each row of X holds numeric package and route features, and
y is the observed delivery time in hours. You must implement ordinary least squares with an intercept in NumPy using the closed-form normal equation. scikit-learn, np.polyfit, and any gradient-descent loop are off limits.
The input X has shape with
rows and
features, and
y has shape . Your function must return the coefficient vector
beta of shape with the intercept stored first, the in-sample predictions, and the coefficient of determination
. Expect the interviewer to push on numerical stability and on what your code does when the design matrix is singular.
Complete the 4 missing operations in the skeleton below and trace the exact array shape after each line. Then verify your fit against np.linalg.lstsq with np.testing.assert_allclose, estimate the flop and memory cost for a million-row training set, and explain when the closed form fails and what you would use instead.
Skeleton Code (Fill Blanks 1-4):
01 import numpy as np
02
03
04 def fit_ols(X: np.ndarray, y: np.ndarray):
05 """Closed-form OLS with intercept. X: (n_samples, n_features), y: (n_samples,)."""
06 X = np.asarray(X, dtype=np.float64)
07 y = np.asarray(y, dtype=np.float64).ravel()
08 n_samples, n_features = X.shape
09 # TODO (Blank 1): prepend an intercept column of ones
10 # X_design has shape (n_samples, n_features + 1); column 0 is the bias
11 X_design = ...
12 # TODO (Blank 2): solve the normal equations for beta, shape (n_features + 1,)
13 # must still return a beta when X is rank-deficient
14 beta = ...
15 # TODO (Blank 3): in-sample predictions and residuals, both (n_samples,)
16 y_hat = ...
17 resid = ...
18 # TODO (Blank 4): coefficient of determination R^2 (scalar)
19 r2 = ...
20 return beta, y_hat, r2
21
22
23 def predict(beta: np.ndarray, X_new: np.ndarray) -> np.ndarray:
24 """Apply fitted beta (intercept first) to new rows X_new: (k, n_features)."""
25 X_new = np.asarray(X_new, dtype=np.float64)
26 return beta[0] + X_new @ beta[1:]
Figure 1: The input and output contract is fixed, and the four linear-algebra steps in between are yours to write with plain NumPy.
1Inspection Checklist (Where to Look)
(1) Intercept Convention: Line 26 reads the bias from beta[0], so the augmented design must agree with that column order and have shape .
(2) Linear-System Route: Decide which NumPy routine handles the system with the fewest flops and the smallest error, and what it does when the system is singular.
(3) Residual Geometry: For a correct fit with an intercept, the residuals are orthogonal to every design column and sum to zero.
(4) Baseline for R-Squared: The score compares your fit against a model that always predicts the mean of y; check that it gives 1 for a perfect fit and 0 for a mean-only fit.
2Visual Review Map (Figure 2)

Figure 2: The shape trace a strong candidate narrates aloud. Every blank shows the target shapes it must produce, and writing the operations that reach them is the exercise.
3Interviewer Nudge & Line Focus
Pin the exact input and output shape of each blank, and answer the check, before writing the NumPy call:
np.ones(n_samples) is 1-D with shape (n_samples,) while X is 2-D. Which NumPy constructor stacks a 1-D vector as a column without an explicit reshape, and on which side must it go so that predict() reads the intercept, not a slope, from beta[0]?
(n_features + 1, n + 1). Does computing its inverse and then multiplying cost more or fewer flops than factoring it once, and which route has the smaller error when the matrix is ill-conditioned? What should your code do when the factorization hits an exactly zero pivot?
(n_samples,)? If y had arrived as an (n_samples, 1) column, what shape would y - y_hat silently broadcast to, and which earlier line already protects you?
y itself or from y after removing its mean, and what does your expression return when every target in the batch is identical?
Leave a Reply