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

  1. most_variable_location(data) -> str

    • Return the column name — considering "NYC" as well as all P towns — whose daily temperature series has the largest standard deviation.
  2. median_nyc_when_town2_hot(data) -> int

    • Filter to days satisfying 90 <= Town2 <= 100 (inclusive at both 90 and 100), 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 an int. Raise ValueError if no day falls in [90, 100].
  3. sum_abs_slopes(data) -> int

    • Fit P single-predictor OLS regressions with intercepts (NYC ~ 1 + Town_j), one for each town column (name != "NYC"). Sum |slope_j| across all P regressions (omitting intercepts; a constant town with zero variance contributes 0.0), and round the final sum half-up to an int.
  4. best_single_town(data) -> str

    • Return the town name whose single-predictor OLS fit (NYC ~ 1 + town) yields the smallest in-sample MSE.
  5. 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-sample MSE.
  6. answer_part1(data) -> Tuple[str, int, int, str, Tuple[str, str]]

    • Return the 5-tuple combining the results of tasks 1 through 5 in order.

Part 2

  1. best_five_towns(data, k: int = 5) -> List[str]
    • Return the k town names (default k = 5, in data's column order) whose joint k-predictor OLS model (NYC ~ 1 + towns) achieves the lowest in-sample MSE. Raise ValueError if data contains fewer than k candidate towns (or k < 0) or 0 rows.

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,000 to 5,000 daily rows (n >= 1) and P ≈ 10 to 30 candidate towns.
  • Every column in data has identical length n and finite floating-point entries (no NaNs); "Town2" is present whenever median_nyc_when_town2_hot or answer_part1 is 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

  1. Understand the table layout and helper utilities

    Each row of data represents one aligned calendar day, "NYC" is the target series we want to predict, and "Town1" … "TownP" (P typically 10 to 30) are candidate predictor towns. Converting columns on demand into 1D float64 NumPy 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-in round() uses round-half-to-even (round(72.5) == 72), whereas math.floor(x + 0.5) rounds .5 halves 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 as 0.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"]
    
  2. 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 length n, 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, slice NYC with 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 82
    

    If zero days fall inside [90, 100], raise ValueError.

    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)
    
  3. 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 slope b in 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, never a_j: Intercepts are excluded. 2. Apply abs() before adding: Otherwise negative slopes cancel positive ones. 3. Check x.max() == x.min() on raw values before centering: Subtracting mean() from [0.3] * 10 leaves ~5.5e-17 IEEE-754 rounding noise rather than exact zeros, turning 0 / 0 into spurious ratios if you only check denominator == 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)
    
  4. 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)²). Calling lstsq directly on n = 3,000 rows for all C(30, 5) = 142,506 subsets repeats 3,000-row projections 142,506 times.

    Two exact linear-algebra steps shrink all n rows down to m ≤ P + 1 ≤ 31 rows 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 reduces y ≈ a + X[:, idx] @ b to y_centered ≈ x_centered[:, idx] @ b. 2. Compress n days into m = min(n, P + 1) rows via thin QR factorization: Factor [x_centered, y_centered] = Q @ R, where Q (n × m) has orthonormal columns (Q.T @ Q = I). Orthogonal transformations preserve Euclidean length, so for every subset idx and slope vector b:

    [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 ||^2
    

    Unlike normal equations (Xc.T @ Xc), thin QR never squares the matrix condition number, preserving full float64 precision on nearly collinear stations while turning each subset fit into a tiny m × k lstsq call independent of n.

    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
    
  5. Q4, Q5, and Q6: Search k-town subsets cleanly

    With SubsetFitter, Q4 (k = 1, P subsets), Q5 (k = 2, P(P - 1)/2 pairs — 435 at P = 30), and Q6 (k = 5, C(30, 5) = 142,506 subsets) all share best_subset(fitter, k). Because itertools.combinations(range(P), k) emits sorted index tuples, [fitter.towns[j] for j in best_idx] automatically preserves data's column order.

    At P ≤ 30, evaluating all 142,506 compressed 31 × 5 fits takes ~1.5 seconds 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)
    
  6. Trace Example 1 by hand

    Walk through Example 1 (4 days, 3 towns) 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: Town3 has the largest variance (21.0, std ≈ 4.58), returning "Town3".
    • Task 2: Town2 lies in [90, 100] on days 1, 2, 3 (91, 97, 99); NYC on those days is [84, 78, 82], median 82.
    • Task 3: Slopes b = (xc · yc) / (xc · xc) are 12 / 4 = 3.00 (Town1), 12 / 68 ≈ 0.1765 (Town2), and 28 / 84 ≈ 0.3333 (Town3). Their absolute sum 3.5098 rounds half-up to 4.
    • Task 4: Single-town RSS = 40 - b · (xc · yc) gives 4.0 (MSE = 1.00) for Town1, 37.88 (MSE = 9.47) for Town2, and 30.67 (MSE = 7.67) for Town3, so "Town1" wins alone.
    • Task 5: Adding xc2 + xc3 day by day yields [-3 + 7, 3 - 5, 5 - 3, -5 + 1] = [4, -2, 2, -4] = yc! Together NYC = -84 + 1·Town2 + 1·Town3 cancels their opposite noise for MSE = 0.0, so ("Town2", "Town3") wins even though neither beat "Town1" individually.
  7. 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 Tasks 1 and 3 because each of the P columns of length n is scanned a constant number of times (O(n) for Task 2, which inspects only Town2 and NYC).
  • Time — Tasks 4, 5, and 6: O(n · P² + C(P, k) · P · k²) (for n ≥ P + 1), because thin QR compresses the n × (P + 1) centered matrix once in O(n · P²) time into m = min(n, P + 1) ≤ P + 1 rows, after which each of the C(P, k) subset checks solves a small m × k least-squares system independent of n.
  • Space: O(n · P) for the centered n × (P + 1) matrix during QR factorization, plus O(P²) for the compressed m × (P + 1) summary R.

Edge cases

  • Constant town column (max == min): Variance is zero so simple slope is undefined; testing col.max() == col.min() before subtracting col.mean() prevents floating-point rounding dust ([0.3] * 10 centers to ~5.5e-17) from corrupting Q3 or Q4–Q6.
  • Zero matching days in 90 ≤ Town2 ≤ 100: median_nyc_when_town2_hot raises ValueError.
  • Boundary values and .5 medians: Both 90.0 and 100.0 are included, and even-length slices average the two middle values before round_half_up rounds .5 halves toward +infinity (72.5 → 73).
  • Duplicate or nearly collinear stations: np.linalg.lstsq on the QR-compressed matrix handles rank deficiency without crashing and preserves accuracy when two stations differ only at 1e-8 scale.
  • Fewer than k candidate towns: best_subset raises ValueError when k > P or k < 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" from most_variable_location: "NYC" is an eligible location whenever its own variance exceeds every town's.
  • Picking argmax(correlation) instead of argmax(|correlation|) in best_single_town: With an intercept, MSE = Var(NYC) · (1 - r²), so r = -0.9 beats r = +0.7.
  • Fitting lstsq(X[:, S], y) without centering or a ones column: Omitting the intercept forces predictions through 0°F.
  • Calling np.linalg.solve on Xc.T @ Xc: solve raises LinAlgError on duplicate columns, and forming Xc.T @ Xc squares the condition number.

Alternative approaches

  • Full-matrix lstsq per subset (np.column_stack([ones, X[:, S]])): Clean and fast enough for k = 1 (30 fits) and k = 2 (435 fits), though ~10× slower for k = 5 (142,506 fits) because every subset re-scans all n rows.
  • Greedy forward selection for best_five_towns: Adds one station per round in 5P - 10 total fits; indispensable when P is 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 = 5 is held fixed, adjusted R² (variance explained penalized for predictor count), AIC, and BIC (penalized log-likelihood criteria adding 2(k + 1) or (k + 1) ln n) rank all 5-town subsets identically to training MSE because n and k are constant; those criteria become active once you also search across model sizes k = 1 … k_max. To guard against overfitting within k = 5 directly, 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 inside fitter.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 · Town2 that swing wildly under tiny data perturbations. That instability ruins coefficient interpretation (individual slopes no longer measure standalone station sensitivity), whereas predictions X @ b remain 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 vector r and orthogonalized candidate columns, selecting the next town maximizing (r · q_j)² / (q_j · q_j) in O(n · P · k) total work (~5,000 vector dot products). Alternatively, fit Lasso (L1-penalized OLS) (adding λ ∑ |b_j| to shrink weak slopes to exact zero), walk the regularization path until 5 stations have non-zero weights, and refit unpenalized OLS on those 5 stations.
  • 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) and yc = y - mean(y), with optimal slope b = (xc · yc) / (xc · xc). Expanding the residual sum of squares gives RSS = ||yc - b · xc||² = (yc · yc) - 2b(xc · yc) + b²(xc · xc) = (yc · yc) - (xc · yc)² / (xc · xc) = ||yc||² · (1 - r²), where r = (xc · yc) / (||xc|| · ||yc||) is Pearson correlation. Since ||yc||² / n = Var(NYC) is constant across all candidate towns, minimizing MSE = RSS / n is algebraically identical to maximizing r², and therefore maximizing |r|.

Follow-up questions

Similar questions

More Two Sigma interview questions

All 55 Two Sigma questions →