Regional Temperature Modeling and Streaming Regression

Medium · Machine Learning · Data Scientist · Online Assessment

Problem Statement

A meteorological analytics team tracks daily temperatures recorded in New York City alongside simultaneous daily readings from several surrounding towns. All series share the same chronological sequence of calendar days, where nyc is a list of floats and towns maps each town's name to an aligned list of floats of equal length.

Implement the following five analytical and modeling components:

  1. Day-to-day temperature volatility (daily_change_volatility, most_volatile_town)

    • Define a town's daily fluctuation as the population standard deviation (ddof = 0) of its consecutive day-over-day temperature differences temps[i] - temps[i - 1] for 1 <= i < len(temps). Raise ValueError when len(temps) < 2.
    • In most_volatile_town(towns), return the name of the town with the highest daily_change_volatility. Break ties in favor of the lexicographically earliest town name, and raise ValueError if towns is empty.
  2. Weather-pattern similarity (pearson, most_similar_town)

    • Implement pearson(a, b) to compute the Pearson correlation coefficient between two equal-length numeric lists. Raise ValueError if len(a) != len(b) or len(a) < 2, and return 0.0 whenever either list is constant (zero variance).
    • In most_similar_town(nyc, towns), measure similarity by taking the Pearson correlation between NYC's day-over-day changes and each town's day-over-day changes. Return the town with the largest correlation, breaking ties lexicographically by town name and raising ValueError if towns is empty (or has fewer than 3 days).
  3. Chronological holdout and linear regression evaluation (split_by_time, validation_mse)

    • In split_by_time(nyc, towns, n_train), partition the timeline so the earliest n_train days form (train_towns, train_nyc) and the remaining days form (val_towns, val_nyc). Return (train_towns, train_nyc, val_towns, val_nyc), raising ValueError unless 0 < n_train < len(nyc).
    • In validation_mse(train_towns, train_nyc, val_towns, val_nyc, names), fit an ordinary least squares (OLS) model with an intercept predicting NYC temperature from the subset of towns listed in names on the training split (using minimum-norm least squares when columns are collinear, and predicting the training mean of train_nyc when names is empty). Return the mean squared error (MSE) on the validation split.
  4. Forward greedy feature selection (greedy_select)

    • Given a feature budget k, start from an empty town list [] and perform k greedy steps. In each step, evaluate every unselected town together with the already chosen towns and append the town that achieves the lowest validation_mse (breaking ties lexicographically by town name).
    • Return (selected_towns, final_val_mse) with selected_towns ordered as chosen. Raise ValueError unless 0 <= k <= len(train_towns).
  5. Origin-constrained linear regression in batch and streaming modes (slope_through_origin, StreamingSlope)

    • Implement single-feature linear regression without an intercept (y = b * x) minimizing squared error sum((y_i - b * x_i)^2).
    • slope_through_origin(xs, ys) computes b over full lists xs and ys at once, raising ValueError if len(xs) != len(ys) and returning 0.0 when xs is empty or every x_i == 0.
    • StreamingSlope maintains the exact same slope online as (x, y) pairs arrive one at a time in O(1) time and O(1) memory without storing historical observations: update(x, y) ingests one pair and returns the updated slope, while slope() returns the current slope (0.0 until at least one nonzero x has been seen).

Examples

Example 1

Input:

nyc = [12.0, 16.0, 14.0, 19.0, 17.0, 20.0]
towns = {
    "bergen": [10.0, 14.0, 12.0, 17.0, 15.0, 18.0],
    "hudson": [8.0, 10.0, 12.0, 14.0, 16.0, 18.0],
    "nassau": [15.0, 9.0, 17.0, 11.0, 19.0, 13.0],
}

Output:

most_volatile_town(towns)  # -> "nassau"
most_similar_town(nyc, towns)  # -> "bergen"
train_t, train_y, val_t, val_y = split_by_time(nyc, towns, n_train=4)
greedy_select(train_t, train_y, val_t, val_y, k=1)  # -> (["bergen"], 0.0)

Explanation: - "hudson" climbs by +2.0 every day, so its day-over-day changes [2, 2, 2, 2, 2] have volatility 0.0. "bergen" has changes [4, -2, 5, -2, 3] (volatility sqrt(9.04) ≈ 3.01), while "nassau" alternates [-6, 8, -6, 8, -6] (volatility sqrt(47.04) ≈ 6.86), making "nassau" the most volatile town. - "bergen" is always 2.0 degrees below NYC, so its daily changes match NYC's identically (pearson = 1.0), making "bergen" the most similar town. - Splitting after day 4 trains on indices 0..3 and validates on indices 4..5 ([17.0, 20.0]). OLS on ["bergen"] fits nyc = 2.0 + 1.0 * bergen, predicting [17.0, 20.0] on validation with 0.0 MSE.

Example 2

Input:

xs = [0.0, 2.0, 4.0, -2.0]
ys = [3.0, 5.0, 9.0, -3.0]

Output:

slope_through_origin(xs, ys)  # -> 2.1666666666666665 (13 / 6)

stream = StreamingSlope()
[stream.update(x, y) for x, y in zip(xs, ys)]
# -> [0.0, 2.5, 2.3, 2.1666666666666665]

Explanation: - After (0.0, 3.0), sum(x^2) = 0.0, so the slope defaults to 0.0. - After (2.0, 5.0), sum(x*y) = 10.0 and sum(x^2) = 4.0, giving 10.0 / 4.0 = 2.5. - After (4.0, 9.0), the running totals reach 46.0 / 20.0 = 2.3. - After (-2.0, -3.0), sum(x*y) = 52.0 and sum(x^2) = 24.0, matching the batch slope 52.0 / 24.0 = 13 / 6.

Constraints

  • All town series in towns have the exact same length as nyc.
  • Volatility requires at least 2 days; daily-change similarity requires at least 3 days; chronological splitting requires 0 < n_train < len(nyc).
  • Feature budget satisfies 0 <= k <= len(towns).
  • Tie-breaking across town names always selects the lexicographically smallest string ("a" < "b").
  • StreamingSlope.update and StreamingSlope.slope must run in O(1) time and O(1) auxiliary space per observation.

Step-by-step walkthrough

  1. Understand the data shape and the five sub-problems

    Picture the historical weather table sorted chronologically from oldest date to newest date. Each row holds one calendar day: New York City's temperature plus the temperature in every nearby town on that same day. Assuming aligned dates with no missing cells (we cover missing dates in the explanation), we represent NYC as a list of floats and the nearby towns as a dictionary mapping each town's name to a list of floats of the same length:

    day index:    0     1     2     3     4     5
    nyc       = [12.0, 16.0, 14.0, 19.0, 17.0, 20.0]
    towns     = {
        "bergen": [10.0, 14.0, 12.0, 17.0, 15.0, 18.0],
        "hudson": [ 8.0, 10.0, 12.0, 14.0, 16.0, 18.0],
        "nassau": [15.0,  9.0, 17.0, 11.0, 19.0, 13.0],
    }
    

    We break the prompt's five parts into small, testable functions:

    Part Goal Functions
    1. Volatility Rank towns by day-to-day temperature jumpiness daily_change_volatility, most_volatile_town
    2. Similarity Find the town whose daily weather moves most like NYC's pearson, most_similar_town
    3. Prediction Split by time, fit linear regression, score validation MSE split_by_time, validation_mse
    4. Feature selection Greedily pick k towns that minimize validation MSE greedy_select
    5. No-intercept slope Fit y = b * x in batch and in O(1) streaming updates slope_through_origin, StreamingSlope

    Whenever two towns tie on a score, we pick the alphabetically earlier town name so every result is deterministic.

  2. Task 1: Measure volatility with day-over-day changes

    Before writing code, we have to define what "temperature fluctuation" means. A tempting first try is the population standard deviation (the square root of the average squared distance from the mean) of a town's raw daily temperatures. Why does that fail? Because raw temperatures across a year are dominated by the slow winter-to-summer seasonal cycle: a town that warms smoothly from 20°F in January to 90°F in July has a huge raw spread even if every single day is barely 0.4°F warmer than the day before.

    To isolate actual day-to-day weather swings, we apply first differencing: we subtract yesterday's temperature from today's (change[i] = temps[i] - temps[i - 1]) and take the population standard deviation of those daily changes. Compare two 6-day towns:

    town      raw temperatures          raw std   daily changes          mean change   change std (volatility)
    "ramp"    [0, 5, 10, 15, 20, 25]     8.54     [5, 5, 5, 5, 5]            5.0        0.00  (perfectly steady)
    "zigzag"  [10, 14, 10, 14, 10, 14]   2.00     [4, -4, 4, -4, 4]          0.8        3.92  (bounces every day)
    

    Notice how "zigzag" gets 3.92: its five daily jumps [4, -4, 4, -4, 4] have mean 4 / 5 = 0.8, squared deviations [3.2^2, (-4.8)^2, 3.2^2, (-4.8)^2, 3.2^2] = [10.24, 23.04, 10.24, 23.04, 10.24], average 76.80 / 5 = 15.36, and square root sqrt(15.36) ≈ 3.92. Raw standard deviation mistakenly picks "ramp"; change volatility picks "zigzag".

    def daily_change_volatility(temps: List[float]) -> float:
        if len(temps) < 2:
            raise ValueError("need at least two days")
        # changes: 1D array of day-over-day jumps [temps[1]-temps[0], temps[2]-temps[1], ...]
        # Differencing removes slow winter-to-summer trends so we measure daily weather swings.
        changes = np.diff(np.asarray(temps, dtype=float))
        # np.std uses ddof=0 by default, giving the population standard deviation.
        return float(np.std(changes))
    
    
    def most_volatile_town(towns: Dict[str, List[float]]) -> str:
        if not towns:
            raise ValueError("no towns")
        # Volatility is always >= 0.0, so initializing best_value to -1.0 guarantees
        # the very first town in sorted order becomes our initial leader.
        best_name = ""
        best_value = -1.0
        # Scan names in alphabetical order and use strict '>' so ties keep the earlier name.
        for name in sorted(towns):
            value = daily_change_volatility(towns[name])
            if value > best_value:
                best_name = name
                best_value = value
        return best_name
    
  3. Task 2: Measure similarity by correlating daily changes

    To measure whether two series share the same pattern even if one town sits on a hill and is always 5°F cooler, we use Pearson correlation: a scale-free score between -1 and +1 that measures how consistently two sequences move above and below their respective averages together.

    dx_i = x_i - mean(x),    dy_i = y_i - mean(y)
    
    r = sum(dx_i * dy_i) / sqrt(sum(dx_i^2) * sum(dy_i^2))
    

    Just like volatility, computing r on raw temperature levels falls into the seasonality trap: every town within 200 miles of NYC is cold in January and hot in July! Suppose the shared seasonal sine wave has variance 72 (amplitude 12°F) while day-to-day local weather has variance 9 (standard deviation 3°F). Even if Town B's daily weather fronts are completely unrelated to NYC's (weather correlation = 0.0) while Town A shares NYC's weather (weather correlation = 0.9), look at what happens:

    metric                         Town A (shared weather)              Town B (unrelated weather)
    raw level correlation          (72 + 0.9 * 9) / 81 = 0.99           (72 + 0.0 * 9) / 81 = 0.89  (looks high!)
    daily-change correlation       about 0.90                           about 0.00                  (cleanly separated)
    

    Differencing strips away the slow seasonal wave, leaving only whether a warm jump in NYC matches a warm jump in the town on that same day. If either change series is completely flat (denominator == 0), correlation is mathematically undefined, so we return 0.0 so a flat series never beats a town that genuinely tracks NYC.

    def pearson(a: List[float], b: List[float]) -> float:
        x = np.asarray(a, dtype=float)
        y = np.asarray(b, dtype=float)
        if len(x) != len(y) or len(x) < 2:
            raise ValueError("need two sequences of the same length >= 2")
        # Center each sequence around its own mean so constant offsets cancel out.
        dx = x - x.mean()
        dy = y - y.mean()
        # Denominator is sqrt(sum(dx^2) * sum(dy^2)); it is 0 iff at least one series is flat.
        sum_sq_x = float(np.sum(dx * dx))
        sum_sq_y = float(np.sum(dy * dy))
        denominator = float(np.sqrt(sum_sq_x * sum_sq_y))
        if denominator == 0.0:
            return 0.0
        numerator = float(np.sum(dx * dy))
        return numerator / denominator
    
    
    def most_similar_town(nyc: List[float], towns: Dict[str, List[float]]) -> str:
        if not towns:
            raise ValueError("no towns")
        # Correlate day-over-day changes rather than raw levels so shared summer/winter
        # seasons do not make unrelated towns look artificially similar.
        nyc_changes = np.diff(np.asarray(nyc, dtype=float))
        best_name = ""
        # Every valid Pearson correlation is >= -1.0, so -2.0 is safely below any town's score.
        best_value = -2.0
        for name in sorted(towns):
            town_changes = np.diff(np.asarray(towns[name], dtype=float))
            value = pearson(list(nyc_changes), list(town_changes))
            if value > best_value:
                best_name = name
                best_value = value
        return best_name
    
  4. Task 3: Chronological split and ordinary least squares prediction

    Now we want to predict NYC's raw temperature from p selected towns using ordinary least squares (OLS): choosing weights b0, b1, ..., bp for nyc_hat = b0 + b1 * town_1 + ... + bp * town_p that minimize the sum of squared prediction errors on the training days. We evaluate accuracy on held-out days with mean squared error (MSE), the average of (predicted - actual)^2.

    Two modeling choices are critical here:

    1. Split chronologically, never randomly. Weather is serially correlated: Tuesday's temperature is very close to Monday's and Wednesday's. If we randomly shuffled days before splitting, Monday and Wednesday would land in training while Tuesday landed in validation — leaking the answer across neighboring days and making MSE look unrealistically small. Instead, the first n_train days form the training period and all remaining days form the future validation period.
    2. Prepend a column of 1s to build the design matrix. A design matrix is simply the 2D table of model inputs (one row per day, one column per parameter). Putting 1.0 in column 0 gives the model an intercept b0 that absorbs constant elevation/latitude offsets between towns and NYC. Better yet, when zero towns are selected (names == []), the design matrix has a single column of 1.0s, so least squares automatically predicts mean(train_nyc) — the natural zero-feature baseline!
     Chronological split (n_train = 3 out of 5 days)         Design matrix X for names = ["a", "b"]
     day:   0    1    2  |   3    4                           row 0: [ 1.0,  a[0],  b[0] ]
           [  training   | validation ]                       row 1: [ 1.0,  a[1],  b[1] ]
                                                              row 2: [ 1.0,  a[2],  b[2] ]
                                                                        ^
                                                                    intercept col
    

    We solve for coefs using np.linalg.lstsq, which uses singular value decomposition (SVD) — a numerically stable matrix factorization that works cleanly even if two towns have identical or collinear temperatures (where inverting X^T X would crash).

    def split_by_time(nyc: List[float], towns: Dict[str, List[float]],
                      n_train: int) -> Tuple[Dict[str, List[float]], List[float], Dict[str, List[float]], List[float]]:
        # Both splits must contain at least one day to fit a model and evaluate MSE.
        if not 0 < n_train < len(nyc):
            raise ValueError("n_train must leave at least one day on each side")
        # train_towns / val_towns: {town_name: [temps_slice]} preserving date order.
        # Slicing chronologically avoids leaking adjacent days between train and validation.
        train_towns: Dict[str, List[float]] = {}
        val_towns: Dict[str, List[float]] = {}
        for name in towns:
            train_towns[name] = list(towns[name][:n_train])
            val_towns[name] = list(towns[name][n_train:])
        train_nyc = list(nyc[:n_train])
        val_nyc = list(nyc[n_train:])
        return train_towns, train_nyc, val_towns, val_nyc
    
    
    def _design_matrix(towns: Dict[str, List[float]], names: List[str], n_rows: int) -> np.ndarray:
        """Build shape (n_rows, len(names) + 1): column 0 of 1s plus one column per town."""
        # Column 0 is all 1.0s for the intercept b0; columns 1..p hold the chosen towns.
        matrix = np.ones((n_rows, len(names) + 1), dtype=float)
        for col_idx, name in enumerate(names):
            matrix[:, col_idx + 1] = towns[name]
        return matrix
    
    
    def validation_mse(train_towns: Dict[str, List[float]], train_nyc: List[float],
                       val_towns: Dict[str, List[float]], val_nyc: List[float],
                       names: List[str]) -> float:
        x_train = _design_matrix(train_towns, names, len(train_nyc))
        x_val = _design_matrix(val_towns, names, len(val_nyc))
        y_train = np.asarray(train_nyc, dtype=float)
        y_val = np.asarray(val_nyc, dtype=float)
        # Solve min ||x_train @ coefs - y_train||_2 via SVD so collinear columns never crash.
        coefs = np.linalg.lstsq(x_train, y_train, rcond=None)[0]
        predictions = x_val @ coefs
        errors = predictions - y_val
        return float(np.mean(errors ** 2))
    
  5. Task 4: Greedy forward selection on validation MSE

    With m candidate towns and a budget of k features, checking every possible subset of size k requires C(m, k) separate regressions (for m = 50, k = 10, that is over 10 billion models!). Greedy forward selection approximates this in k quick rounds: start with selected = [], and in each round try appending each unused town one at a time, fit OLS on the training split, and permanently add whichever town gives the lowest validation MSE.

    Why must we score candidates on validation MSE rather than training MSE? Because adding an extra column to OLS gives the solver one more knob to turn — training MSE can never go up, even for pure noise! Suppose on 6 training days nyc = [1, 2, 3, 4, 5, 6], town "leaky" equals [1, 2, 3, 4, 5, 6] by coincidence on training days (training MSE = 0.0) but reverses to [10, 9, 8, 7] on validation days nyc = [7, 8, 9, 10] (validation MSE = 5.0), whereas "honest" tracks NYC with minor noise (validation MSE = 11/14 ≈ 0.786). Scoring on validation MSE rightly picks "honest".

    Let's trace a 2-step run where true nyc = 10 * a + b and town "c" is distracting noise:

    train (4 days): a = [1, -1, 1, -1], b = [1, 1, -1, -1], c = [3, 1, 2, 5], nyc = [11, -9, 9, -11]
    val   (3 days): a = [2, 0, -1],     b = [1, -2, 0],     c = [1, 2, 3],    nyc = [21, -2, -10]
    
    round   candidate subset   fitted model on train     val errors                 val MSE
    start   []                 nyc_hat = 0               [-21, 2, 10]               545 / 3 = 181.67
      1     ["a"]              nyc_hat = 10*a            [-1, 2, 0]                 5 / 3   =   1.67  <-- winner
      1     ["b"]              nyc_hat = 1*b             [-20, 0, 10]               500 / 3 = 166.67
      1     ["c"]              nyc_hat = 12.1 - 4.4*c    [-13.3, 5.3, 8.9]          146.99
      2     ["a", "b"]         nyc_hat = 10*a + 1*b      [0, 0, 0]                  0.00              <-- winner
      2     ["a", "c"]         nyc_hat = -1.1 + 10.2*a + 0.4*c                      1.81
    
    returned: (["a", "b"], 0.0)
    
    def greedy_select(train_towns: Dict[str, List[float]], train_nyc: List[float],
                      val_towns: Dict[str, List[float]], val_nyc: List[float],
                      k: int) -> Tuple[List[str], float]:
        if not 0 <= k <= len(train_towns):
            raise ValueError("k must be between 0 and the number of towns")
        # selected: list of chosen town names in the exact order they were added, e.g. ["a", "b"].
        selected: List[str] = []
        current_mse = validation_mse(train_towns, train_nyc, val_towns, val_nyc, selected)
        # In each of the k rounds, test every unselected town on validation MSE (not training MSE).
        for _ in range(k):
            best_name = ""
            best_mse = float("inf")
            # Sorted iteration + strict '<' breaks MSE ties in favor of the alphabetically first town.
            for name in sorted(train_towns):
                if name in selected:
                    continue
                candidate_names = selected + [name]
                candidate_mse = validation_mse(train_towns, train_nyc, val_towns, val_nyc, candidate_names)
                if candidate_mse < best_mse:
                    best_name = name
                    best_mse = candidate_mse
            selected.append(best_name)
            current_mse = best_mse
        return selected, current_mse
    

    Note that the prompt asks for exactly k towns, so the loop runs k iterations even if round k nudges validation MSE slightly upward (in production you can also mention early stopping when no candidate improves current_mse).

  6. Task 5 (batch): Derive no-intercept linear regression from scratch

    In no-intercept regression, our line is forced through the origin (0, 0): y_hat = b * x, with a single slope parameter b and no + b0. Let's derive the exact formula by writing down the sum of squared errors L(b) and setting its derivative with respect to b to zero:

    1. Objective:           L(b)  = sum_i (y_i - b * x_i)^2
    2. Differentiate:       dL/db = sum_i 2 * (y_i - b * x_i) * (-x_i)
                                  = -2 * sum_i (x_i * y_i) + 2 * b * sum_i (x_i^2)
    3. Set dL/db = 0:       b * sum_i (x_i^2) = sum_i (x_i * y_i)
    4. Solve for b:         b = sum_i (x_i * y_i) / sum_i (x_i^2)
    

    Because the second derivative d^2L / db^2 = 2 * sum_i (x_i^2) is non-negative, this b is guaranteed to minimize squared error. Notice that b is not the usual with-intercept formula cov(x, y) / var(x) — here we do not subtract mean(x) or mean(y)! On Example 2 (xs = [0.0, 2.0, 4.0, -2.0] and ys = [3.0, 5.0, 9.0, -3.0]):

    • sum_xy = 0*3 + 2*5 + 4*9 + (-2)*(-3) = 0 + 10 + 36 + 6 = 52
    • sum_xx = 0^2 + 2^2 + 4^2 + (-2)^2 = 0 + 4 + 16 + 4 = 24
    • No-intercept slope: 52 / 24 = 13 / 6 ≈ 2.167 (whereas with-intercept regression fits y_hat = 1.5 + 2.0 * x).

    What if every single x_i is 0 (or the input lists are empty)? Then b * 0 = 0 for every b, so all slopes produce identical errors; returning 0.0 gives the standard minimum-norm solution without dividing by zero.

    def slope_through_origin(xs: List[float], ys: List[float]) -> float:
        if len(xs) != len(ys):
            raise ValueError("xs and ys must have the same length")
        # Accumulate sufficient statistics sum(x_i * y_i) and sum(x_i^2) in one pass.
        sum_xy = 0.0
        sum_xx = 0.0
        for x, y in zip(xs, ys):
            sum_xy += x * y
            sum_xx += x * x
        # When every x is 0, any slope b gives identical predictions (0); return minimum-norm 0.0.
        if sum_xx == 0.0:
            return 0.0
        return sum_xy / sum_xx
    
  7. Task 5 (streaming): Update the slope in O(1) with running sums

    Look back at b = sum(x_i * y_i) / sum(x_i^2). Both the numerator and denominator are plain sums! In statistics, (sum_xy, sum_xx) are called sufficient statistics: fixed-size summaries of past data that hold 100% of the information needed to compute the exact answer without keeping any historical rows.

    Whenever a new (x, y) pair arrives on a live stream, we add x * y to self.sum_xy, add x * x to self.sum_xx, and divide — O(1) time and O(1) memory per observation, whether we have seen 3 points or 3 billion points:

    arrival #   new (x, y)    x * y   x * x   running sum_xy   running sum_xx   current slope
       1        ( 0.0,  3.0)    0.0     0.0           0.0              0.0         0.0  (sum_xx == 0 guard)
       2        ( 2.0,  5.0)   10.0     4.0          10.0              4.0        10.0 /  4.0 = 2.5
       3        ( 4.0,  9.0)   36.0    16.0          46.0             20.0        46.0 / 20.0 = 2.3
       4        (-2.0, -3.0)    6.0     4.0          52.0             24.0        52.0 / 24.0 = 2.1667 (13/6)
    

    (Algebraically, you can also rewrite b_n as an error-correction step b_n = b_{n-1} + x_n * (y_n - b_{n-1} * x_n) / sum_xx_n, known as 1D recursive least squares, which produces the exact same numbers: 2.5 + 4 * (9 - 2.5 * 4) / 20 = 2.3. Keeping sum_xy and sum_xx directly is cleaner and has fewer edge-case divisions.)

    class StreamingSlope:
        """No-intercept slope updated one (x, y) pair at a time in O(1)."""
    
        def __init__(self) -> None:
            # Store only the two running sums instead of the full history of (x, y) pairs.
            self.sum_xy = 0.0
            self.sum_xx = 0.0
    
        def update(self, x: float, y: float) -> float:
            """Add one pair and return the slope over every pair seen so far."""
            self.sum_xy += x * y
            self.sum_xx += x * x
            return self.slope()
    
        def slope(self) -> float:
            """Current slope; 0.0 until some x != 0 has arrived."""
            if self.sum_xx == 0.0:
                return 0.0
            return self.sum_xy / self.sum_xx
    
  8. Complete solution

    Putting all five parts together gives the complete module:

    from typing import Dict, List, Tuple
    
    import numpy as np
    
    
    def daily_change_volatility(temps: List[float]) -> float:
        """Fluctuation of one town: the population standard deviation of its
        day-over-day changes temps[i] - temps[i - 1].
    
        Raise ValueError if there are fewer than two days.
        """
        if len(temps) < 2:
            raise ValueError("need at least two days")
        # changes: 1D array of day-over-day jumps [temps[1]-temps[0], temps[2]-temps[1], ...]
        # Differencing removes slow winter-to-summer trends so we measure daily weather swings.
        changes = np.diff(np.asarray(temps, dtype=float))
        # np.std uses ddof=0 by default, giving the population standard deviation.
        return float(np.std(changes))
    
    
    def most_volatile_town(towns: Dict[str, List[float]]) -> str:
        """Name of the town with the largest daily_change_volatility.
    
        Ties go to the alphabetically first name. Raise ValueError if towns is empty.
        """
        if not towns:
            raise ValueError("no towns")
        # Volatility is always >= 0.0, so initializing best_value to -1.0 guarantees
        # the very first town in sorted order becomes our initial leader.
        best_name = ""
        best_value = -1.0
        # Scan names in alphabetical order and use strict '>' so ties keep the earlier name.
        for name in sorted(towns):
            value = daily_change_volatility(towns[name])
            if value > best_value:
                best_name = name
                best_value = value
        return best_name
    
    
    def pearson(a: List[float], b: List[float]) -> float:
        """Pearson correlation of two equal-length sequences.
    
        Return 0.0 when either sequence is constant (the correlation is undefined).
        Raise ValueError if the lengths differ or are below 2.
        """
        x = np.asarray(a, dtype=float)
        y = np.asarray(b, dtype=float)
        if len(x) != len(y) or len(x) < 2:
            raise ValueError("need two sequences of the same length >= 2")
        # Center each sequence around its own mean so constant offsets cancel out.
        dx = x - x.mean()
        dy = y - y.mean()
        # Denominator is sqrt(sum(dx^2) * sum(dy^2)); it is 0 iff at least one series is flat.
        sum_sq_x = float(np.sum(dx * dx))
        sum_sq_y = float(np.sum(dy * dy))
        denominator = float(np.sqrt(sum_sq_x * sum_sq_y))
        if denominator == 0.0:
            return 0.0
        numerator = float(np.sum(dx * dy))
        return numerator / denominator
    
    
    def most_similar_town(nyc: List[float], towns: Dict[str, List[float]]) -> str:
        """Town whose day-over-day changes have the highest Pearson correlation
        with NYC's day-over-day changes. Ties go to the alphabetically first name.
        """
        if not towns:
            raise ValueError("no towns")
        # Correlate day-over-day changes rather than raw levels so shared summer/winter
        # seasons do not make unrelated towns look artificially similar.
        nyc_changes = np.diff(np.asarray(nyc, dtype=float))
        best_name = ""
        # Every valid Pearson correlation is >= -1.0, so -2.0 is safely below any town's score.
        best_value = -2.0
        for name in sorted(towns):
            town_changes = np.diff(np.asarray(towns[name], dtype=float))
            value = pearson(list(nyc_changes), list(town_changes))
            if value > best_value:
                best_name = name
                best_value = value
        return best_name
    
    
    def split_by_time(nyc: List[float], towns: Dict[str, List[float]],
                      n_train: int) -> Tuple[Dict[str, List[float]], List[float], Dict[str, List[float]], List[float]]:
        """Chronological split: the first n_train days train, the rest validate.
    
        Returns (train_towns, train_nyc, val_towns, val_nyc).
        Raise ValueError unless 0 < n_train < len(nyc).
        """
        # Both splits must contain at least one day to fit a model and evaluate MSE.
        if not 0 < n_train < len(nyc):
            raise ValueError("n_train must leave at least one day on each side")
        # train_towns / val_towns: {town_name: [temps_slice]} preserving date order.
        # Slicing chronologically avoids leaking adjacent days between train and validation.
        train_towns: Dict[str, List[float]] = {}
        val_towns: Dict[str, List[float]] = {}
        for name in towns:
            train_towns[name] = list(towns[name][:n_train])
            val_towns[name] = list(towns[name][n_train:])
        train_nyc = list(nyc[:n_train])
        val_nyc = list(nyc[n_train:])
        return train_towns, train_nyc, val_towns, val_nyc
    
    
    def _design_matrix(towns: Dict[str, List[float]], names: List[str], n_rows: int) -> np.ndarray:
        """Build shape (n_rows, len(names) + 1): column 0 of 1s plus one column per town."""
        # Column 0 is all 1.0s for the intercept b0; columns 1..p hold the chosen towns.
        matrix = np.ones((n_rows, len(names) + 1), dtype=float)
        for col_idx, name in enumerate(names):
            matrix[:, col_idx + 1] = towns[name]
        return matrix
    
    
    def validation_mse(train_towns: Dict[str, List[float]], train_nyc: List[float],
                       val_towns: Dict[str, List[float]], val_nyc: List[float],
                       names: List[str]) -> float:
        """Fit least squares with an intercept on the towns in `names` (train rows),
        then return the mean squared error on the validation rows.
    
        With names == [] the model predicts the training mean of NYC.
        """
        x_train = _design_matrix(train_towns, names, len(train_nyc))
        x_val = _design_matrix(val_towns, names, len(val_nyc))
        y_train = np.asarray(train_nyc, dtype=float)
        y_val = np.asarray(val_nyc, dtype=float)
        # Solve min ||x_train @ coefs - y_train||_2 via SVD so collinear columns never crash.
        coefs = np.linalg.lstsq(x_train, y_train, rcond=None)[0]
        predictions = x_val @ coefs
        errors = predictions - y_val
        return float(np.mean(errors ** 2))
    
    
    def greedy_select(train_towns: Dict[str, List[float]], train_nyc: List[float],
                      val_towns: Dict[str, List[float]], val_nyc: List[float],
                      k: int) -> Tuple[List[str], float]:
        """Forward selection of k towns by validation MSE.
    
        Each step adds the town with the lowest validation MSE together with the
        towns already chosen (ties: alphabetically first). Returns the towns in the
        order they were added and the validation MSE of the final model.
        Raise ValueError unless 0 <= k <= number of towns.
        """
        if not 0 <= k <= len(train_towns):
            raise ValueError("k must be between 0 and the number of towns")
        # selected: list of chosen town names in the exact order they were added, e.g. ["a", "b"].
        selected: List[str] = []
        current_mse = validation_mse(train_towns, train_nyc, val_towns, val_nyc, selected)
        # In each of the k rounds, test every unselected town on validation MSE (not training MSE).
        for _ in range(k):
            best_name = ""
            best_mse = float("inf")
            # Sorted iteration + strict '<' breaks MSE ties in favor of the alphabetically first town.
            for name in sorted(train_towns):
                if name in selected:
                    continue
                candidate_names = selected + [name]
                candidate_mse = validation_mse(train_towns, train_nyc, val_towns, val_nyc, candidate_names)
                if candidate_mse < best_mse:
                    best_name = name
                    best_mse = candidate_mse
            selected.append(best_name)
            current_mse = best_mse
        return selected, current_mse
    
    
    def slope_through_origin(xs: List[float], ys: List[float]) -> float:
        """Least-squares slope b of y = b * x (no intercept), all data at once.
    
        Return 0.0 when every x is 0 (the minimum-norm solution).
        Raise ValueError if the lengths differ.
        """
        if len(xs) != len(ys):
            raise ValueError("xs and ys must have the same length")
        # Accumulate sufficient statistics sum(x_i * y_i) and sum(x_i^2) in one pass.
        sum_xy = 0.0
        sum_xx = 0.0
        for x, y in zip(xs, ys):
            sum_xy += x * y
            sum_xx += x * x
        # When every x is 0, any slope b gives identical predictions (0); return minimum-norm 0.0.
        if sum_xx == 0.0:
            return 0.0
        return sum_xy / sum_xx
    
    
    class StreamingSlope:
        """No-intercept slope updated one (x, y) pair at a time in O(1)."""
    
        def __init__(self) -> None:
            # Store only the two running sums instead of the full history of (x, y) pairs.
            self.sum_xy = 0.0
            self.sum_xx = 0.0
    
        def update(self, x: float, y: float) -> float:
            """Add one pair and return the slope over every pair seen so far."""
            self.sum_xy += x * y
            self.sum_xx += x * x
            return self.slope()
    
        def slope(self) -> float:
            """Current slope; 0.0 until some x != 0 has arrived."""
            if self.sum_xx == 0.0:
                return 0.0
            return self.sum_xy / self.sum_xx
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of daily temperatures as ripples riding on top of a giant ocean tide. The ocean tide is the slow winter-to-summer seasonal cycle that lifts and lowers every town in the region together over months, while the ripples are the sharp day-to-day weather fronts we actually feel from one day to the next. Across all five parts of this problem, our guiding habits are to separate fast daily changes from slow seasonal drift, test predictive models strictly on future days, and reduce streaming formulas to small running totals.

Naive shortcuts fail at every stage here. Taking the standard deviation (the square root of the average squared distance from the mean) or Pearson correlation (a -1 to +1 score of how closely two series move together around their means) on raw temperatures mostly measures the shared seasonal tide rather than daily weather. Randomly shuffling days before splitting leaks neighboring days across training and validation, scoring greedy features on training mean squared error (MSE) (the average squared prediction error) rewards overfitting (memorizing training noise that fails on future data), and saving every past (x, y) pair in a live stream turns a constant-time update into a growing linear scan.

Walk through our 6-day sample to see each idea in action:

  • Suppose nyc = [12, 16, 14, 19, 17, 20], bergen = [10, 14, 12, 17, 15, 18] (always 2° cooler, identical jumps), hudson = [8, 10, 12, 14, 16, 18] (a smooth +2° ramp), and nassau = [15, 9, 17, 11, 19, 13] (sharp alternating swings).
  • First differencing (subtracting consecutive days temps[i] - temps[i - 1]) gives hudson jumps [2, 2, 2, 2, 2] (volatility 0.0), bergen jumps [4, -2, 5, -2, 3] (volatility 3.01), and nassau jumps [-6, 8, -6, 8, -6] (volatility 6.86), while change correlation gives bergen a perfect 1.0 with NYC.
  • For ordinary least squares (OLS) (fitting a linear equation y_hat = b0 + b1 * x1 + ... that minimizes squared error), splitting chronologically after day 4 fits nyc = 2.0 + 1.0 * bergen on days 0..3 and predicts [17, 20] on days 4..5 (validation MSE = 0.0).
  • For no-intercept streaming regression (y = b * x), each arriving pair (x, y) updates just two sufficient statistics (fixed-size summaries holding all needed history): sum_xy += x * y and sum_xx += x * x. Across (0, 3), (2, 5), (4, 9), (-2, -3), we accumulate sum_xy = 52 and sum_xx = 24, returning b = 52 / 24 = 13 / 6 ≈ 2.167 in O(1) work.

Complexity

Let m be the number of towns, n be the total number of days (n_train + n_val), and k be the number of selected towns (assuming the standard regression regime n_train >= k + 1):

  • Volatility and similarity (most_volatile_town, most_similar_town): O(m * n + m log m) time and O(n) extra space. Sorting the m town names takes O(m log m), and for each town we scan its n days once to compute n - 1 daily differences and their standard deviation or correlation, holding only one town's change array in memory at a time.
  • Single regression evaluation (validation_mse with p towns): O(n * p^2) time and O(n * p) space. Building the training and validation design matrices (2D input tables of shape rows x (p + 1)) takes O(n * p) memory and time, solving least squares via singular value decomposition (SVD) (a stable matrix factorization) takes O(n_train * p^2) time, and multiplying validation inputs by the (p + 1) weights takes O(n_val * p) time.
  • Greedy forward selection (greedy_select): O(m * n * k^3 + m log m) time and O(n * k) space. In round s (1 <= s <= k), we try up to m remaining towns, and each fit solves an s-town regression in O(n * s^2) time; summing m * n * s^2 from s = 1 to k gives O(m * n * k^3).
  • Batch no-intercept slope (slope_through_origin): O(n) time and O(1) extra space, because we sweep through the n pairs once while updating two scalar floats (sum_xy and sum_xx).
  • Streaming no-intercept slope (StreamingSlope.update, slope): O(1) time and O(1) space per update, because each arriving pair performs two multiplications, two additions, and one division on two stored floats.

Edge cases

  • Fewer than two or three days: daily_change_volatility needs at least 2 days to form 1 daily change (ValueError otherwise). most_similar_town correlates daily changes, and pearson requires at least 2 points, so similarity needs at least 3 days of raw temperatures.
  • Constant series or constant daily ramps: When a sequence has zero spread, the denominator of pearson is 0.0. Returning 0.0 prevents a division-by-zero crash and ensures a flat series never beats a positively correlated town. (With floating-point arithmetic, values like [0.1, 0.2, 0.3] have differences 0.1 and 0.09999999999999998; in production data with rounding noise, guard denominator < 1e-12 if near-constant ramps appear.)
  • Alphabetical ties: Iterating over sorted(towns) with strict > (for maximization) or strict < (for MSE minimization) guarantees the alphabetically earliest town wins every tie.
  • Zero selected towns (k = 0): greedy_select(..., k=0) skips the loop and returns ([], baseline_mse), where the intercept-only design matrix predicts mean(train_nyc) on every validation day.
  • Collinear or duplicate towns: Two towns with identical readings make X^T X non-invertible, which crashes normal-equation solvers (np.linalg.inv), whereas SVD-based np.linalg.lstsq cleanly returns the minimum-norm solution.
  • All x = 0 in no-intercept regression: Before any nonzero x arrives (sum_xx == 0.0), every slope b predicts b * 0 = 0; returning 0.0 matches the minimum-norm convention cleanly.

Common mistakes

  • Using raw temperature standard deviation for volatility: This ranks inland continental climates above coastal ones because of winter-to-summer range rather than day-to-day weather swings.
  • Correlating raw temperature levels for similarity: Shared seasons inflate almost every nearby town's correlation above 0.85, masking which town actually shares daily weather fronts with NYC.
  • Randomly shuffling rows before train/validation split: Adjacent calendar days are strongly correlated (autocorrelation), so a random split causes data leakage (validation answers sneaking into neighboring training days) and produces overly optimistic MSE.
  • Selecting greedy features by training MSE instead of validation MSE: Adding any column to OLS never increases training MSE, so training-set selection blindly picks overfit or noisy features.
  • Treating the greedy validation MSE as an unbiased test score: Because we actively searched over towns to minimize validation MSE, that final number has selection bias; always report final expected error on a third, later test split.
  • Using the with-intercept slope formula cov(x, y) / var(x) for Task 5: Centering x and y fits a nonzero intercept b0 = mean(y) - b * mean(x); a line forced through (0, 0) requires uncentered sum(x * y) / sum(x^2).
  • Appending every (x, y) pair to a list inside StreamingSlope: Recomputing the sums from scratch makes update O(n) time and O(n) memory instead of O(1).

Alternative approaches

  • Volatility metrics: Mean absolute daily change mean(|temps[i] - temps[i - 1]|) reduces sensitivity to rare freak storms; standard deviation of seasonal anomalies (temperature minus that calendar date's multi-year historical average) captures multi-day heatwaves and cold snaps as well as 1-day jumps.
  • Similarity metrics: Root mean squared error (RMSE) on raw levels is better than correlation if the business question is "which town's thermometer could directly substitute for a broken NYC sensor without recalibration?"
  • Feature selection: Lasso regression (linear regression with an L1 penalty lambda * sum(|b_j|) that shrinks unhelpful weights to exact zero) selects features in a single convex optimization per lambda rather than m * k separate fits.

Follow-up questions

  • Does greedy forward selection always discover the globally optimal subset of k towns? No. Suppose town_a = signal + storm_noise and town_b = storm_noise, where storm_noise is huge and nyc = signal = town_a - town_b. Alone, neither town_a nor town_b correlates strongly with NYC, so round 1 picks a mediocre town_c instead; with k = 2, greedy can never recover the exact zero-error pair ["a", "b"] that exhaustive C(m, 2) search would find.
  • How should the pipeline change when weather stations drop out or leave missing calendar dates? First align every series on an explicit calendar date index rather than list positions, and compute day-over-day changes only across consecutive calendar dates (date[i] - date[i - 1] == 1 day) so a 5-day outage is never treated as a 1-day jump. For regression, evaluate all candidate towns on the exact same non-missing validation dates (imputing short gaps using only past values on the same side of the train/validation split so future data never leaks backward).
  • How can the O(1) streaming slope adapt if the true relationship drifts gradually over time? Replace plain addition with exponential forgetting (multiplying old totals by a decay factor 0 < gamma < 1 before adding the new point): sum_xy = gamma * sum_xy + x * y and sum_xx = gamma * sum_xx + x * x. A factor like gamma = 0.99 gives an effective memory window of roughly 1 / (1 - gamma) = 100 recent observations while keeping every update O(1) in time and space.
  • Under what physical or statistical conditions is omitting the intercept justified for temperature series? Only when x = 0 genuinely implies E[y] = 0, such as when both x and y represent centered anomalies or day-over-day temperature changes. On raw temperatures, a zero-intercept slope isn't even invariant to unit conversion: x = [0, 10]°C and y = [5, 15]°C give b = 150 / 100 = 1.50, whereas the exact same days in Fahrenheit (x = [32, 50]°F, y = [41, 59]°F) shift the origin and change the slope to 4262 / 3524 ≈ 1.21.

Follow-up questions

Similar questions

More Two Sigma interview questions

All 55 Two Sigma questions →