OLS Subset Selection for NYC Daily Temperatures
Medium · Machine Learning · Quantitative Researcher · Technical Screen
Problem Statement
You are given an aligned multi-year table data of daily Fahrenheit temperature observations containing "NYC" alongside P surrounding weather stations ("Town1", "Town2", ..., "TownP"). Each key in data maps a column name to a sequence of floats of equal length n (1 entry per calendar day, with zero missing values; data may be a Python dict or a pandas-style column mapping).
Throughout all tasks:
- Every linear model is an ordinary least squares (OLS) regression with an intercept (NYC ~ 1 + predictors), evaluated by in-sample mean squared error (MSE) across all n rows (mean((NYC - y_hat) ** 2)).
- Whenever an integer-rounded value is requested, round only the final quantity to the nearest integer using half-up rounding (exact .5 halves round toward +infinity, e.g., 72.5 -> 73 and -2.5 -> -2).
- Break any exact ties deterministically by choosing the earliest column (or lexicographically earliest column-index tuple) in data's column iteration order.
Implement the seven functions declared in starter.py:
Part 1
-
most_variable_location(data) -> str- Return the column name — considering
"NYC"as well as allPtowns — whose daily temperature series has the largest standard deviation.
- Return the column name — considering
-
median_nyc_when_town2_hot(data) -> int- Filter to days satisfying
90 <= Town2 <= 100(inclusive at both90and100), compute the median of"NYC"on those filtered days (averaging the two middle values if the matching day count is even), and round half-up to anint. RaiseValueErrorif no day falls in[90, 100].
- Filter to days satisfying
-
sum_abs_slopes(data) -> int- Fit
Psingle-predictor OLS regressions with intercepts (NYC ~ 1 + Town_j), one for each town column (name != "NYC"). Sum|slope_j|across allPregressions (omitting intercepts; a constant town with zero variance contributes0.0), and round the final sum half-up to anint.
- Fit
-
best_single_town(data) -> str- Return the town name whose single-predictor OLS fit (
NYC ~ 1 + town) yields the smallest in-sampleMSE.
- Return the town name whose single-predictor OLS fit (
-
best_town_pair(data) -> Tuple[str, str]- Return the 2-tuple of town names (ordered as their columns appear in
data) whose joint two-predictor OLS fit (NYC ~ 1 + town_a + town_b) yields the smallest in-sampleMSE.
- Return the 2-tuple of town names (ordered as their columns appear in
-
answer_part1(data) -> Tuple[str, int, int, str, Tuple[str, str]]- Return the 5-tuple combining the results of tasks
1through5in order.
- Return the 5-tuple combining the results of tasks
Part 2
best_five_towns(data, k: int = 5) -> List[str]- Return the
ktown names (defaultk = 5, indata's column order) whose jointk-predictor OLS model (NYC ~ 1 + towns) achieves the lowest in-sampleMSE. RaiseValueErrorifdatacontains fewer thankcandidate towns (ork < 0) or0rows.
- Return the
Examples
Example 1 (Part 1: answer_part1)
Input:
data = {
"NYC": [84, 78, 82, 76],
"Town1": [61, 59, 61, 59],
"Town2": [91, 97, 99, 89],
"Town3": [77, 65, 67, 71],
}
Output:
("Town3", 82, 4, "Town1", ("Town2", "Town3"))
Explanation:
- Task 1 (most_variable_location): Population variances around means (80, 60, 94, 70) are 10.0 (NYC), 1.0 (Town1), 17.0 (Town2), and 21.0 (Town3), so "Town3" has the widest spread.
- Task 2 (median_nyc_when_town2_hot): Town2 lies in [90, 100] on days 1, 2, 3 (91, 97, 99); corresponding NYC values are [84, 78, 82], whose median is 82.
- Task 3 (sum_abs_slopes): Simple OLS slopes are 3.0 (Town1), 3/17 ≈ 0.1765 (Town2), and 1/3 ≈ 0.3333 (Town3). Their absolute sum 3.5098 rounds half-up to 4.
- Task 4 (best_single_town): Single-town MSEs are 1.00 (Town1), 9.47 (Town2), and 7.67 (Town3), so "Town1" wins alone.
- Task 5 (best_town_pair): Together, NYC = -84 + 1.0 * Town2 + 1.0 * Town3 cancels opposite deviations between Town2 and Town3 for an exact MSE = 0.0, returning ("Town2", "Town3").
Example 2 (Part 2: best_five_towns)
Input:
data = {
"NYC": [79, 75, 77, 73, 75, 71, 75],
"Town1": [61, 59, 60, 60, 60, 60, 60],
"Town2": [95, 95, 96, 94, 95, 95, 95],
"Town3": [51, 51, 51, 51, 51, 51, 44],
"Town4": [65, 65, 65, 65, 66, 64, 65],
"Town5": [71, 71, 69, 69, 70, 70, 70],
"Town6": [81, 81, 81, 81, 78, 78, 80],
}
Output:
["Town1", "Town2", "Town4", "Town5", "Town6"]
Explanation: NYC = -635 + 2*Town1 + 2*Town2 + 2*Town4 + Town5 + Town6 reconstructs all 7 daily NYC readings with MSE = 0.0, whereas "Town3" varies orthogonally to "NYC" and leaves strictly positive residual error if substituted for any of the five chosen stations.
Constraints
- Typical datasets span
n ≈ 1,000to5,000daily rows (n >= 1) andP ≈ 10to30candidate towns. - Every column in
datahas identical lengthnand finite floating-point entries (noNaNs);"Town2"is present whenevermedian_nyc_when_town2_hotoranswer_part1is called. - Town columns may include constant series (zero variance), exact duplicates, or nearly collinear series (
TownB ≈ TownA + 1e-8 * signal), so linear-algebra routines must remain numerically stable and rank-tolerant.
Step-by-step walkthrough
Understand the table layout and helper utilities
Each row of
datarepresents one aligned calendar day,"NYC"is the target series we want to predict, and"Town1" … "TownP"(Ptypically10to30) are candidate predictor towns. Converting columns on demand into1Dfloat64NumPy arrays keeps memory compact and vector math fast across thousands of days.Before implementing the seven functions, pin down three edge behaviors: - Half-up rounding on
.5: Python's built-inround()uses round-half-to-even (round(72.5) == 72), whereasmath.floor(x + 0.5)rounds.5halves consistently toward+infinity(72.5 → 73,-2.5 → -2). - Deterministic tie-breaking: Updating the best candidate only on strict<or>preserves the earliest column (or lexicographically earliest column-index tuple) when scores tie. - Zero-variance towns: If a town's readings never vary (max == min), its single-predictor slope is undefined (0 / 0); we count its slope contribution as0.0.from typing import Dict, List, Sequence, Tuple import itertools import math import numpy as np Data = Dict[str, Sequence[float]] def round_half_up(value: float) -> int: """Round to the nearest integer with exact .5 halves rounded toward +infinity.""" # Python's built-in round() uses round-half-to-even (round(72.5) == 72), # whereas floor(value + 0.5) sends 72.5 -> 73 and -2.5 -> -2 consistently. return int(math.floor(value + 0.5)) def column(data: Data, name: str) -> np.ndarray: """Extract one location column as a 1D float64 NumPy array of shape (n,).""" return np.asarray(data[name], dtype=float) def town_names(data: Data) -> List[str]: """Return candidate town names in their original column order, excluding NYC.""" return [name for name in data if name != "NYC"]Q1 and Q2: Find the widest spread and filter hot Town2 days
Q1 (
most_variable_location): Standard deviation measures root-mean-square spread around a column's mean (√(mean((x - mean(x))²))). Remember that"NYC"itself is eligible alongside all towns. Also note that population (1 / n) and sample (1 / (n - 1)) conventions produce identical rankings because every column has the same lengthn, scaling every column's standard deviation by the same positive constant√(n / (n - 1)).Q2 (
median_nyc_when_town2_hot): Construct a boolean mask(town2 >= 90.0) & (town2 <= 100.0)including both endpoints, sliceNYCwith that mask, and compute the median (the middle sorted entry, or the average of the two middle entries on an even count) before rounding half-up:Day 1 2 3 4 Town2 91 97 99 89 -> mask (90 <= Town2 <= 100): [True, True, True, False] NYC 84 78 82 76 -> NYC[mask] = [84, 78, 82] -> sorted [78, 82, 84] -> median 82If zero days fall inside
[90, 100], raiseValueError.def most_variable_location(data: Data) -> str: """Q1: name of the column (NYC included) with the largest standard deviation.""" # Every column has the same length n, so population std (1/n) and sample std (1/(n-1)) # differ by the same constant factor sqrt(n / (n - 1)) and produce identical rankings. best_name = None best_std = -1.0 for name in data: col_std = float(np.std(column(data, name))) if col_std > best_std: best_name = name best_std = col_std return best_name def median_nyc_when_town2_hot(data: Data) -> int: """Q2: median NYC temperature over days with 90 <= Town2 <= 100, rounded half up.""" nyc_temps = column(data, "NYC") town2_temps = column(data, "Town2") # Include both boundary values 90.0 and 100.0 in the hot-day filter. hot_day_mask = (town2_temps >= 90.0) & (town2_temps <= 100.0) if not hot_day_mask.any(): raise ValueError("no day has Town2 temperature between 90 and 100 inclusive") hot_nyc_median = float(np.median(nyc_temps[hot_day_mask])) return round_half_up(hot_nyc_median)Q3: Sum the absolute simple-regression slopes
In single-predictor ordinary least squares (OLS) (
NYC = a + b · Town), subtracting each column's mean (x_centered = x - mean(x),y_centered = y - mean(y)) gives the slopebin closed form:b = (x_centered . y_centered) / (x_centered . x_centered) a = mean(y) - b * mean(x)Avoid three common pitfalls in
sum_abs_slopes: 1. Sum|b_j|only, nevera_j: Intercepts are excluded. 2. Applyabs()before adding: Otherwise negative slopes cancel positive ones. 3. Checkx.max() == x.min()on raw values before centering: Subtractingmean()from[0.3] * 10leaves~5.5e-17IEEE-754 rounding noise rather than exact zeros, turning0 / 0into spurious ratios if you only checkdenominator == 0.def simple_slope(x: np.ndarray, y: np.ndarray) -> float: """Return OLS slope b of y = a + b * x, or 0.0 when x has zero variance.""" # Guard constant columns on raw values before centering to avoid dividing ~1e-32 by ~1e-32. if x.max() == x.min(): return 0.0 x_centered = x - x.mean() y_centered = y - y.mean() numerator = float(x_centered @ y_centered) denominator = float(x_centered @ x_centered) return numerator / denominator def sum_abs_slopes(data: Data) -> int: """Q3: sum of |slope| across all P simple regressions NYC ~ 1 + town, rounded half up.""" nyc_temps = column(data, "NYC") total_abs_slope = 0.0 for town in town_names(data): town_temps = column(data, town) # Sum |b| only — exclude intercepts and take abs() so negative slopes do not cancel positive ones. slope = simple_slope(town_temps, nyc_temps) total_abs_slope += abs(slope) return round_half_up(total_abs_slope)Key idea for Q4–Q6: Center columns and compress n days with thin QR
Tasks 4, 5, and 6 ask for the
k-town subset (k = 1, 2, 5) that minimizes in-sample mean squared error (MSE)mean((NYC - y_hat)²). Callinglstsqdirectly onn = 3,000rows for allC(30, 5) = 142,506subsets repeats3,000-row projections142,506times.Two exact linear-algebra steps shrink all
nrows down tom ≤ P + 1 ≤ 31rows once up front: 1. Center every column to eliminate the intercept: Because any OLS fit with an intercept passes through(mean(X), mean(y)), subtracting column means reducesy ≈ a + X[:, idx] @ btoy_centered ≈ x_centered[:, idx] @ b. 2. Compressndays intom = min(n, P + 1)rows via thin QR factorization: Factor[x_centered, y_centered] = Q @ R, whereQ(n × m) has orthonormal columns (Q.T @ Q = I). Orthogonal transformations preserve Euclidean length, so for every subsetidxand slope vectorb:[x_centered | y_centered] = Q @ [ rx | ry ] n x (P + 1) n x m m x P m x 1 (m <= P + 1 <= 31) || y_centered - x_centered[:, idx] @ b ||^2 == || ry - rx[:, idx] @ b ||^2Unlike normal equations (
Xc.T @ Xc), thinQRnever squares the matrix condition number, preserving fullfloat64precision on nearly collinear stations while turning each subset fit into a tinym × klstsqcall independent ofn.class SubsetFitter: """Evaluates in-sample MSE of NYC ~ 1 + (subset of towns) using one thin QR compression.""" def __init__(self, data: Data): # self.towns: list of P town names in column order, e.g. ["Town1", ..., "TownP"] self.towns = town_names(data) y = column(data, "NYC") self.n = len(y) if self.n == 0: raise ValueError("NYC column must contain at least one day") # Phase 1: Center NYC and every town column to remove the regression intercept. # Because an OLS plane with an intercept always passes through (mean(X), mean(y)), # fitting y = a + X b is identical to fitting (y - mean(y)) = (X - mean(X)) b. y_centered = y - y.mean() p = len(self.towns) x_centered = np.zeros((self.n, p), dtype=float) for j, town in enumerate(self.towns): col = column(data, town) # Check max > min before subtracting the mean: centering [0.3] * 10 leaves # ~5.5e-17 float rounding noise instead of exact zeros. if col.max() > col.min(): x_centered[:, j] = col - col.mean() # Phase 2: Compress all n days into m <= P + 1 rows once via thin QR factorization. # Writing [x_centered, y_centered] = Q @ R where Q has orthonormal columns (Q.T @ Q = I), # rotating by Q.T preserves Euclidean length: # ||y_centered - x_centered[:, idx] @ b||^2 == ||ry - rx[:, idx] @ b||^2. # Unlike normal equations (Xc.T @ Xc), QR never squares the condition number, # so nearly collinear towns keep full float64 accuracy while each subset fit costs O(m * k^2). augmented = np.column_stack([x_centered, y_centered]) _, r_matrix = np.linalg.qr(augmented, mode="reduced") # self.rx: shape (m, P) compressed town matrix; self.ry: shape (m,) compressed NYC vector self.rx = r_matrix[:, :p] self.ry = r_matrix[:, p] def mse(self, idx: List[int]) -> float: """Return in-sample MSE for the subset of town indices `idx`.""" sub_rx = self.rx[:, idx] # Use lstsq rather than solve because duplicate or collinear towns make sub_rx rank-deficient. coef = np.linalg.lstsq(sub_rx, self.ry, rcond=None)[0] residuals = self.ry - sub_rx @ coef rss = float(residuals @ residuals) return rss / self.nQ4, Q5, and Q6: Search k-town subsets cleanly
With
SubsetFitter, Q4 (k = 1,Psubsets), Q5 (k = 2,P(P - 1)/2pairs —435atP = 30), and Q6 (k = 5,C(30, 5) = 142,506subsets) all sharebest_subset(fitter, k). Becauseitertools.combinations(range(P), k)emits sorted index tuples,[fitter.towns[j] for j in best_idx]automatically preservesdata's column order.At
P ≤ 30, evaluating all142,506compressed31 × 5fits takes ~1.5seconds and guarantees the exact minimum-MSE 5-town subset — avoiding greedy forward selection's failure mode on complementary predictors whose individual noise cancels out only jointly.def best_subset(fitter: SubsetFitter, k: int) -> List[str]: """Search all k-town combinations and return the lowest-MSE subset in column order.""" if k < 0 or k > len(fitter.towns): raise ValueError(f"need between 0 and {len(fitter.towns)} towns, got {k}") # best_idx: tuple of k integer indices into fitter.towns achieving best_mse so far best_idx = None best_mse = math.inf for idx in itertools.combinations(range(len(fitter.towns)), k): candidate_mse = fitter.mse(list(idx)) # Strict `<` keeps the earliest combination in column order when two subsets tie. if candidate_mse < best_mse: best_idx = idx best_mse = candidate_mse return [fitter.towns[j] for j in best_idx] def best_single_town(data: Data) -> str: """Q4: town whose simple linear regression NYC ~ 1 + town achieves the lowest MSE.""" fitter = SubsetFitter(data) return best_subset(fitter, 1)[0] def best_town_pair(data: Data) -> Tuple[str, str]: """Q5: pair of towns (in column order) whose joint OLS model achieves the lowest MSE.""" fitter = SubsetFitter(data) first_town, second_town = best_subset(fitter, 2) return first_town, second_town def answer_part1(data: Data) -> Tuple[str, int, int, str, Tuple[str, str]]: """Return the answers to Q1..Q5 as a 5-tuple.""" return ( most_variable_location(data), median_nyc_when_town2_hot(data), sum_abs_slopes(data), best_single_town(data), best_town_pair(data), ) def best_five_towns(data: Data, k: int = 5) -> List[str]: """Q6: the k towns (in column order) whose joint OLS model achieves the lowest MSE.""" fitter = SubsetFitter(data) return best_subset(fitter, k)Trace Example 1 by hand
Walk through Example 1 (
4days,3towns) to verify all five Part 1 outputs and see why the best pair need not contain the best single predictor:Column Raw daily values Mean Centered values (col - mean) Pop. variance ------ ------------------ ---- ---------------------------- ------------- NYC [84, 78, 82, 76] 80 yc = [ 4, -2, 2, -4] 40 / 4 = 10.0 Town1 [61, 59, 61, 59] 60 xc1 = [ 1, -1, 1, -1] 4 / 4 = 1.0 Town2 [91, 97, 99, 89] 94 xc2 = [-3, 3, 5, -5] 68 / 4 = 17.0 Town3 [77, 65, 67, 71] 70 xc3 = [ 7, -5, -3, 1] 84 / 4 = 21.0- Task 1:
Town3has the largest variance (21.0,std ≈ 4.58), returning"Town3". - Task 2:
Town2lies in[90, 100]on days1, 2, 3(91, 97, 99);NYCon those days is[84, 78, 82], median82. - Task 3: Slopes
b = (xc · yc) / (xc · xc)are12 / 4 = 3.00(Town1),12 / 68 ≈ 0.1765(Town2), and28 / 84 ≈ 0.3333(Town3). Their absolute sum3.5098rounds half-up to4. - Task 4: Single-town
RSS = 40 - b · (xc · yc)gives4.0(MSE = 1.00) forTown1,37.88(MSE = 9.47) forTown2, and30.67(MSE = 7.67) forTown3, so"Town1"wins alone. - Task 5: Adding
xc2 + xc3day by day yields[-3 + 7, 3 - 5, 5 - 3, -5 + 1] = [4, -2, 2, -4] = yc! TogetherNYC = -84 + 1·Town2 + 1·Town3cancels their opposite noise forMSE = 0.0, so("Town2", "Town3")wins even though neither beat"Town1"individually.
- Task 1:
Put the complete solution together
Combine the helpers,
SubsetFitter, and task entry points into the complete module:from typing import Dict, List, Sequence, Tuple import itertools import math import numpy as np # `data` maps each location name to its aligned daily temperatures, e.g.: # {"NYC": [73.0, 71.0, ...], "Town1": [54.0, 48.0, ...], ...}. # Every key except "NYC" is a candidate predictor town. Data = Dict[str, Sequence[float]] def round_half_up(value: float) -> int: """Round to the nearest integer with exact .5 halves rounded toward +infinity.""" # Python's built-in round() uses round-half-to-even (round(72.5) == 72), # whereas floor(value + 0.5) sends 72.5 -> 73 and -2.5 -> -2 consistently. return int(math.floor(value + 0.5)) def column(data: Data, name: str) -> np.ndarray: """Extract one location column as a 1D float64 NumPy array of shape (n,).""" return np.asarray(data[name], dtype=float) def town_names(data: Data) -> List[str]: """Return candidate town names in their original column order, excluding NYC.""" return [name for name in data if name != "NYC"] class SubsetFitter: """Evaluates in-sample MSE of NYC ~ 1 + (subset of towns) using one thin QR compression.""" def __init__(self, data: Data): # self.towns: list of P town names in column order, e.g. ["Town1", ..., "TownP"] self.towns = town_names(data) y = column(data, "NYC") self.n = len(y) if self.n == 0: raise ValueError("NYC column must contain at least one day") # Phase 1: Center NYC and every town column to remove the regression intercept. # Because an OLS plane with an intercept always passes through (mean(X), mean(y)), # fitting y = a + X b is identical to fitting (y - mean(y)) = (X - mean(X)) b. y_centered = y - y.mean() p = len(self.towns) x_centered = np.zeros((self.n, p), dtype=float) for j, town in enumerate(self.towns): col = column(data, town) # Check max > min before subtracting the mean: centering [0.3] * 10 leaves # ~5.5e-17 float rounding noise instead of exact zeros. if col.max() > col.min(): x_centered[:, j] = col - col.mean() # Phase 2: Compress all n days into m <= P + 1 rows once via thin QR factorization. # Writing [x_centered, y_centered] = Q @ R where Q has orthonormal columns (Q.T @ Q = I), # rotating by Q.T preserves Euclidean length: # ||y_centered - x_centered[:, idx] @ b||^2 == ||ry - rx[:, idx] @ b||^2. # Unlike normal equations (Xc.T @ Xc), QR never squares the condition number, # so nearly collinear towns keep full float64 accuracy while each subset fit costs O(m * k^2). augmented = np.column_stack([x_centered, y_centered]) _, r_matrix = np.linalg.qr(augmented, mode="reduced") # self.rx: shape (m, P) compressed town matrix; self.ry: shape (m,) compressed NYC vector self.rx = r_matrix[:, :p] self.ry = r_matrix[:, p] def mse(self, idx: List[int]) -> float: """Return in-sample MSE for the subset of town indices `idx`.""" sub_rx = self.rx[:, idx] # Use lstsq rather than solve because duplicate or collinear towns make sub_rx rank-deficient. coef = np.linalg.lstsq(sub_rx, self.ry, rcond=None)[0] residuals = self.ry - sub_rx @ coef rss = float(residuals @ residuals) return rss / self.n def best_subset(fitter: SubsetFitter, k: int) -> List[str]: """Search all k-town combinations and return the lowest-MSE subset in column order.""" if k < 0 or k > len(fitter.towns): raise ValueError(f"need between 0 and {len(fitter.towns)} towns, got {k}") # best_idx: tuple of k integer indices into fitter.towns achieving best_mse so far best_idx = None best_mse = math.inf for idx in itertools.combinations(range(len(fitter.towns)), k): candidate_mse = fitter.mse(list(idx)) # Strict `<` keeps the earliest combination in column order when two subsets tie. if candidate_mse < best_mse: best_idx = idx best_mse = candidate_mse return [fitter.towns[j] for j in best_idx] def most_variable_location(data: Data) -> str: """Q1: name of the column (NYC included) with the largest standard deviation.""" # Every column has the same length n, so population std (1/n) and sample std (1/(n-1)) # differ by the same constant factor sqrt(n / (n - 1)) and produce identical rankings. best_name = None best_std = -1.0 for name in data: col_std = float(np.std(column(data, name))) if col_std > best_std: best_name = name best_std = col_std return best_name def median_nyc_when_town2_hot(data: Data) -> int: """Q2: median NYC temperature over days with 90 <= Town2 <= 100, rounded half up.""" nyc_temps = column(data, "NYC") town2_temps = column(data, "Town2") # Include both boundary values 90.0 and 100.0 in the hot-day filter. hot_day_mask = (town2_temps >= 90.0) & (town2_temps <= 100.0) if not hot_day_mask.any(): raise ValueError("no day has Town2 temperature between 90 and 100 inclusive") hot_nyc_median = float(np.median(nyc_temps[hot_day_mask])) return round_half_up(hot_nyc_median) def simple_slope(x: np.ndarray, y: np.ndarray) -> float: """Return OLS slope b of y = a + b * x, or 0.0 when x has zero variance.""" # Guard constant columns on raw values before centering to avoid dividing ~1e-32 by ~1e-32. if x.max() == x.min(): return 0.0 x_centered = x - x.mean() y_centered = y - y.mean() numerator = float(x_centered @ y_centered) denominator = float(x_centered @ x_centered) return numerator / denominator def sum_abs_slopes(data: Data) -> int: """Q3: sum of |slope| across all P simple regressions NYC ~ 1 + town, rounded half up.""" nyc_temps = column(data, "NYC") total_abs_slope = 0.0 for town in town_names(data): town_temps = column(data, town) # Sum |b| only — exclude intercepts and take abs() so negative slopes do not cancel positive ones. slope = simple_slope(town_temps, nyc_temps) total_abs_slope += abs(slope) return round_half_up(total_abs_slope) def best_single_town(data: Data) -> str: """Q4: town whose simple linear regression NYC ~ 1 + town achieves the lowest MSE.""" fitter = SubsetFitter(data) return best_subset(fitter, 1)[0] def best_town_pair(data: Data) -> Tuple[str, str]: """Q5: pair of towns (in column order) whose joint OLS model achieves the lowest MSE.""" fitter = SubsetFitter(data) first_town, second_town = best_subset(fitter, 2) return first_town, second_town def answer_part1(data: Data) -> Tuple[str, int, int, str, Tuple[str, str]]: """Return the answers to Q1..Q5 as a 5-tuple.""" return ( most_variable_location(data), median_nyc_when_town2_hot(data), sum_abs_slopes(data), best_single_town(data), best_town_pair(data), ) def best_five_towns(data: Data, k: int = 5) -> List[str]: """Q6: the k towns (in column order) whose joint OLS model achieves the lowest MSE.""" fitter = SubsetFitter(data) return best_subset(fitter, k)✅ Submit now — all tests should pass.
Intuition & how it works
Picture the P surrounding towns as regional weather stations and ordinary least squares (OLS) (fitting a line or hyperplane that minimizes average squared prediction error) as combining chosen stations' readings plus an offset to reconstruct NYC's daily temperature. Because every OLS plane with an intercept passes through all columns' sample means, subtracting each column's mean eliminates the intercept up front, and thin QR factorization (projecting n daily rows onto an orthonormal basis of at most P + 1 rows) compresses thousands of days into a compact (P + 1) × (P + 1) upper-triangular summary R with identical residual error for every subset.
Three tempting shortcuts fail here. Running lstsq directly on 3,000 × 6 raw arrays across all C(30, 5) = 142,506 subsets repeats full 3,000-day scans on every combination; compressing via normal equations Xc.T @ Xc squares the condition number and loses floating-point accuracy on nearly identical stations; and greedy forward selection (adding one town per round) misses subsets whose opposite local noise cancels out only when combined.
Walk through Example 1 (NYC = [84, 78, 82, 76], Town1 = [61, 59, 61, 59], Town2 = [91, 97, 99, 89], Town3 = [77, 65, 67, 71]):
1. Centering: Subtracting column means (80, 60, 94, 70) produces yc = [4, -2, 2, -4], xc1 = [1, -1, 1, -1], xc2 = [-3, 3, 5, -5], and xc3 = [7, -5, -3, 1].
2. Summaries (Tasks 1–3): Town3 has the largest spread (variance = 21.0); on the 3 days with 90 ≤ Town2 ≤ 100, NYC is [84, 78, 82] with median 82; and the three simple slopes 3.0, 3/17 ≈ 0.1765, and 1/3 ≈ 0.3333 have absolute sum 3.5098 → 4.
3. Single vs pair subset search (Tasks 4–5): Individually, Town1 achieves MSE = 1.00 (best single predictor), while Town2 (MSE = 9.47) and Town3 (MSE = 7.67) carry heavy local noise; yet together xc2 + xc3 = [4, -2, 2, -4] = yc cancels that noise completely for MSE = 0.0, making ("Town2", "Town3") the winning pair.
Complexity
- Time — Tasks 1, 2, and 3:
O(n · P)for Tasks1and3because each of thePcolumns of lengthnis scanned a constant number of times (O(n)for Task2, which inspects onlyTown2andNYC). - Time — Tasks 4, 5, and 6:
O(n · P² + C(P, k) · P · k²)(forn ≥ P + 1), because thin QR compresses then × (P + 1)centered matrix once inO(n · P²)time intom = min(n, P + 1) ≤ P + 1rows, after which each of theC(P, k)subset checks solves a smallm × kleast-squares system independent ofn. - Space:
O(n · P)for the centeredn × (P + 1)matrix during QR factorization, plusO(P²)for the compressedm × (P + 1)summaryR.
Edge cases
- Constant town column (
max == min): Variance is zero so simple slope is undefined; testingcol.max() == col.min()before subtractingcol.mean()prevents floating-point rounding dust ([0.3] * 10centers to~5.5e-17) from corrupting Q3 or Q4–Q6. - Zero matching days in
90 ≤ Town2 ≤ 100:median_nyc_when_town2_hotraisesValueError. - Boundary values and
.5medians: Both90.0and100.0are included, and even-length slices average the two middle values beforeround_half_uprounds.5halves toward+infinity(72.5 → 73). - Duplicate or nearly collinear stations:
np.linalg.lstsqon the QR-compressed matrix handles rank deficiency without crashing and preserves accuracy when two stations differ only at1e-8scale. - Fewer than
kcandidate towns:best_subsetraisesValueErrorwhenk > Pork < 0. - Exact MSE ties: Strict
<comparison preserves the earliest candidate in column order.
Common mistakes
- Calling Python's built-in
round()instead of half-up rounding:round(72.5) == 72(banker's rounding to even), disagreeing with half-up rounding on even halves. - Including intercepts or signed slopes in
sum_abs_slopes: Intercepts are excluded, and signed slopes let negative correlations cancel positive ones. - Excluding
"NYC"frommost_variable_location:"NYC"is an eligible location whenever its own variance exceeds every town's. - Picking
argmax(correlation)instead ofargmax(|correlation|)inbest_single_town: With an intercept,MSE = Var(NYC) · (1 - r²), sor = -0.9beatsr = +0.7. - Fitting
lstsq(X[:, S], y)without centering or a ones column: Omitting the intercept forces predictions through0°F. - Calling
np.linalg.solveonXc.T @ Xc:solveraisesLinAlgErroron duplicate columns, and formingXc.T @ Xcsquares the condition number.
Alternative approaches
- Full-matrix
lstsqper subset (np.column_stack([ones, X[:, S]])): Clean and fast enough fork = 1(30fits) andk = 2(435fits), though ~10×slower fork = 5(142,506fits) because every subset re-scans allnrows. - Greedy forward selection for
best_five_towns: Adds one station per round in5P - 10total fits; indispensable whenPis hundreds or thousands, at the cost of missing noise-canceling groups on adversarial inputs.
Follow-up questions
- Adding extra predictors never increases training MSE; which evaluation criterion would you substitute in Q6 to penalize overfitting, and how would the implementation change? When
k = 5is held fixed, adjusted R² (variance explained penalized for predictor count), AIC, and BIC (penalized log-likelihood criteria adding2(k + 1)or(k + 1) ln n) rank all5-town subsets identically to training MSE becausenandkare constant; those criteria become active once you also search across model sizesk = 1 … k_max. To guard against overfitting withink = 5directly, evaluate time-blocked cross-validated MSE — holding out contiguous multi-month or yearly blocks rather than random days because daily temperatures have strong temporal autocorrelation (adjacent days share weather systems). In code, precompute one QR summary per training fold and average out-of-fold validation MSE insidefitter.mse(idx). - How does strong multicollinearity between two neighboring towns affect fitted slope estimates in multi-town models, and when is that a problem? When two stations move nearly in lockstep (
r ≈ 0.99), each slope's sampling variance inflates by its Variance Inflation Factor (VIF) (1 / (1 - R_j²) ≈ 50), allowing huge opposing weights like+50.5 · Town1 - 49.5 · Town2that swing wildly under tiny data perturbations. That instability ruins coefficient interpretation (individual slopes no longer measure standalone station sensitivity), whereas predictionsX @ bremain stable and accurate whenever future observations preserve the same collinearity structure between the two towns. - If the dataset expanded to 1,000 candidate weather stations, how would you select five predictors without evaluating trillions of combinations? At
P = 1,000,C(1000, 5) ≈ 8.25 × 10¹²subsets makes exhaustive search infeasible, so switch to polynomial-time subset selection. Orthogonal Matching Pursuit (greedy forward selection with incremental QR updates) tracks the current residual vectorrand orthogonalized candidate columns, selecting the next town maximizing(r · q_j)² / (q_j · q_j)inO(n · P · k)total work (~5,000vector dot products). Alternatively, fit Lasso (L1-penalized OLS) (addingλ ∑ |b_j|to shrink weak slopes to exact zero), walk the regularization path until5stations have non-zero weights, and refit unpenalized OLS on those5stations. - Show mathematically why minimizing single-predictor OLS MSE with an intercept is equivalent to maximizing absolute Pearson correlation with NYC. Including an intercept centers both series to
xc = x - mean(x)andyc = y - mean(y), with optimal slopeb = (xc · yc) / (xc · xc). Expanding the residual sum of squares givesRSS = ||yc - b · xc||² = (yc · yc) - 2b(xc · yc) + b²(xc · xc) = (yc · yc) - (xc · yc)² / (xc · xc) = ||yc||² · (1 - r²), wherer = (xc · yc) / (||xc|| · ||yc||)is Pearson correlation. Since||yc||² / n = Var(NYC)is constant across all candidate towns, minimizingMSE = RSS / nis algebraically identical to maximizingr², and therefore maximizing|r|.
Follow-up questions
- Adding extra predictors never increases training MSE; which evaluation criterion would you substitute in Q6 to penalize overfitting, and how would the implementation change?
- How does strong multicollinearity between two neighboring towns affect fitted slope estimates in multi-town models, and when is that a problem?
- If the dataset expanded to 1,000 candidate weather stations, how would you select five predictors without evaluating trillions of combinations?
- Show mathematically why minimizing single-predictor OLS MSE with an intercept is equivalent to maximizing absolute Pearson correlation with NYC.
Similar questions
- Regional Temperature Modeling and Streaming Regression
- End-to-End Residential Property Valuation Modeling
- Correlation Matrix Constraints and Omitted-Regressor Bias
- Residential Property Valuation Pipeline Design
- Feature Engineering and Loss Selection for Home Valuation
- 24-Hour Station Dock Availability Forecasting
More Two Sigma interview questions
- Piecewise Linear Curve Evaluator Medium
- Regional Temperature Modeling and Streaming Regression Medium
- Polyline Interpolation and Extrapolation Medium Pro
- Scalable Quantitative Portfolio Optimization Platform Medium Pro
- Bounded Piecewise Linear Curve Evaluation Medium Pro
- Price-Time Limit Order Book Engine Medium Pro
- Deterministic Frequency-Tree String Codec Hard Pro
- Price-Time Priority Order Book Engine Medium Pro
- Column-Wise Addition of Decimal Strings Hard Pro
- Top Borough-Hour Taxi Speed Medians Medium Pro