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:
-
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 differencestemps[i] - temps[i - 1]for1 <= i < len(temps). RaiseValueErrorwhenlen(temps) < 2. - In
most_volatile_town(towns), return the name of the town with the highestdaily_change_volatility. Break ties in favor of the lexicographically earliest town name, and raiseValueErroriftownsis empty.
- Define a town's daily fluctuation as the population standard deviation (
-
Weather-pattern similarity (
pearson,most_similar_town)- Implement
pearson(a, b)to compute the Pearson correlation coefficient between two equal-length numeric lists. RaiseValueErroriflen(a) != len(b)orlen(a) < 2, and return0.0whenever 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 raisingValueErroriftownsis empty (or has fewer than 3 days).
- Implement
-
Chronological holdout and linear regression evaluation (
split_by_time,validation_mse)- In
split_by_time(nyc, towns, n_train), partition the timeline so the earliestn_traindays form(train_towns, train_nyc)and the remaining days form(val_towns, val_nyc). Return(train_towns, train_nyc, val_towns, val_nyc), raisingValueErrorunless0 < 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 innameson the training split (using minimum-norm least squares when columns are collinear, and predicting the training mean oftrain_nycwhennamesis empty). Return the mean squared error (MSE) on the validation split.
- In
-
Forward greedy feature selection (
greedy_select)- Given a feature budget
k, start from an empty town list[]and performkgreedy steps. In each step, evaluate every unselected town together with the already chosen towns and append the town that achieves the lowestvalidation_mse(breaking ties lexicographically by town name). - Return
(selected_towns, final_val_mse)withselected_townsordered as chosen. RaiseValueErrorunless0 <= k <= len(train_towns).
- Given a feature budget
-
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 errorsum((y_i - b * x_i)^2). slope_through_origin(xs, ys)computesbover full listsxsandysat once, raisingValueErroriflen(xs) != len(ys)and returning0.0whenxsis empty or everyx_i == 0.StreamingSlopemaintains the exact same slope online as(x, y)pairs arrive one at a time inO(1)time andO(1)memory without storing historical observations:update(x, y)ingests one pair and returns the updated slope, whileslope()returns the current slope (0.0until at least one nonzeroxhas been seen).
- Implement single-feature linear regression without an intercept (
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
townshave the exact same length asnyc. - Volatility requires at least
2days; daily-change similarity requires at least3days; chronological splitting requires0 < 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.updateandStreamingSlope.slopemust run inO(1)time andO(1)auxiliary space per observation.
Step-by-step walkthrough
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_town2. Similarity Find the town whose daily weather moves most like NYC's pearson,most_similar_town3. Prediction Split by time, fit linear regression, score validation MSE split_by_time,validation_mse4. Feature selection Greedily pick ktowns that minimize validation MSEgreedy_select5. No-intercept slope Fit y = b * xin batch and inO(1)streaming updatesslope_through_origin,StreamingSlopeWhenever two towns tie on a score, we pick the alphabetically earlier town name so every result is deterministic.
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"gets3.92: its five daily jumps[4, -4, 4, -4, 4]have mean4 / 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], average76.80 / 5 = 15.36, and square rootsqrt(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_nameTask 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
-1and+1that 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
ron 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 variance72(amplitude 12°F) while day-to-day local weather has variance9(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 return0.0so 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_nameTask 3: Chronological split and ordinary least squares prediction
Now we want to predict NYC's raw temperature from
pselected towns using ordinary least squares (OLS): choosing weightsb0, b1, ..., bpfornyc_hat = b0 + b1 * town_1 + ... + bp * town_pthat 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:
- 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_traindays form the training period and all remaining days form the future validation period. - 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). Putting1.0in column0gives the model an interceptb0that absorbs constant elevation/latitude offsets between towns and NYC. Better yet, when zero towns are selected (names == []), the design matrix has a single column of1.0s, so least squares automatically predictsmean(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 colWe solve for
coefsusingnp.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 invertingX^T Xwould 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))- 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
Task 4: Greedy forward selection on validation MSE
With
mcandidate towns and a budget ofkfeatures, checking every possible subset of sizekrequiresC(m, k)separate regressions (form = 50, k = 10, that is over 10 billion models!). Greedy forward selection approximates this inkquick rounds: start withselected = [], 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 daysnyc = [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 + band 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_mseNote that the prompt asks for exactly
ktowns, so the loop runskiterations even if roundknudges validation MSE slightly upward (in production you can also mention early stopping when no candidate improvescurrent_mse).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 parameterband no+ b0. Let's derive the exact formula by writing down the sum of squared errorsL(b)and setting its derivative with respect tobto 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, thisbis guaranteed to minimize squared error. Notice thatbis not the usual with-intercept formulacov(x, y) / var(x)— here we do not subtractmean(x)ormean(y)! On Example 2 (xs = [0.0, 2.0, 4.0, -2.0]andys = [3.0, 5.0, 9.0, -3.0]):sum_xy = 0*3 + 2*5 + 4*9 + (-2)*(-3) = 0 + 10 + 36 + 6 = 52sum_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 fitsy_hat = 1.5 + 2.0 * x).
What if every single
x_iis0(or the input lists are empty)? Thenb * 0 = 0for everyb, so all slopes produce identical errors; returning0.0gives 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_xxTask 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 addx * ytoself.sum_xy, addx * xtoself.sum_xx, and divide —O(1)time andO(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_nas an error-correction stepb_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. Keepingsum_xyandsum_xxdirectly 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_xxComplete 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), andnassau = [15, 9, 17, 11, 19, 13](sharp alternating swings). - First differencing (subtracting consecutive days
temps[i] - temps[i - 1]) giveshudsonjumps[2, 2, 2, 2, 2](volatility0.0),bergenjumps[4, -2, 5, -2, 3](volatility3.01), andnassaujumps[-6, 8, -6, 8, -6](volatility6.86), while change correlation givesbergena perfect1.0with NYC. - For ordinary least squares (OLS) (fitting a linear equation
y_hat = b0 + b1 * x1 + ...that minimizes squared error), splitting chronologically after day 4 fitsnyc = 2.0 + 1.0 * bergenon days0..3and predicts[17, 20]on days4..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 * yandsum_xx += x * x. Across(0, 3),(2, 5),(4, 9),(-2, -3), we accumulatesum_xy = 52andsum_xx = 24, returningb = 52 / 24 = 13 / 6 ≈ 2.167inO(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 andO(n)extra space. Sorting themtown names takesO(m log m), and for each town we scan itsndays once to computen - 1daily differences and their standard deviation or correlation, holding only one town's change array in memory at a time. - Single regression evaluation (
validation_msewithptowns):O(n * p^2)time andO(n * p)space. Building the training and validation design matrices (2D input tables of shaperows x (p + 1)) takesO(n * p)memory and time, solving least squares via singular value decomposition (SVD) (a stable matrix factorization) takesO(n_train * p^2)time, and multiplying validation inputs by the(p + 1)weights takesO(n_val * p)time. - Greedy forward selection (
greedy_select):O(m * n * k^3 + m log m)time andO(n * k)space. In rounds(1 <= s <= k), we try up tomremaining towns, and each fit solves ans-town regression inO(n * s^2)time; summingm * n * s^2froms = 1tokgivesO(m * n * k^3). - Batch no-intercept slope (
slope_through_origin):O(n)time andO(1)extra space, because we sweep through thenpairs once while updating two scalar floats (sum_xyandsum_xx). - Streaming no-intercept slope (
StreamingSlope.update,slope):O(1)time andO(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_volatilityneeds at least 2 days to form 1 daily change (ValueErrorotherwise).most_similar_towncorrelates daily changes, andpearsonrequires 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
pearsonis0.0. Returning0.0prevents 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 differences0.1and0.09999999999999998; in production data with rounding noise, guarddenominator < 1e-12if 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 predictsmean(train_nyc)on every validation day. - Collinear or duplicate towns: Two towns with identical readings make
X^T Xnon-invertible, which crashes normal-equation solvers (np.linalg.inv), whereas SVD-basednp.linalg.lstsqcleanly returns the minimum-norm solution. - All
x = 0in no-intercept regression: Before any nonzeroxarrives (sum_xx == 0.0), every slopebpredictsb * 0 = 0; returning0.0matches 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: Centeringxandyfits a nonzero interceptb0 = mean(y) - b * mean(x); a line forced through(0, 0)requires uncenteredsum(x * y) / sum(x^2). - Appending every
(x, y)pair to a list insideStreamingSlope: Recomputing the sums from scratch makesupdateO(n)time andO(n)memory instead ofO(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
L1penaltylambda * sum(|b_j|)that shrinks unhelpful weights to exact zero) selects features in a single convex optimization perlambdarather thanm * kseparate fits.
Follow-up questions
- Does greedy forward selection always discover the globally optimal subset of k towns? No. Suppose
town_a = signal + storm_noiseandtown_b = storm_noise, wherestorm_noiseis huge andnyc = signal = town_a - town_b. Alone, neithertown_anortown_bcorrelates strongly with NYC, so round 1 picks a mediocretown_cinstead; withk = 2, greedy can never recover the exact zero-error pair["a", "b"]that exhaustiveC(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 < 1before adding the new point):sum_xy = gamma * sum_xy + x * yandsum_xx = gamma * sum_xx + x * x. A factor likegamma = 0.99gives an effective memory window of roughly1 / (1 - gamma) = 100recent observations while keeping every updateO(1)in time and space. - Under what physical or statistical conditions is omitting the intercept justified for temperature series? Only when
x = 0genuinely impliesE[y] = 0, such as when bothxandyrepresent 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]°Candy = [5, 15]°Cgiveb = 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 to4262 / 3524 ≈ 1.21.
Follow-up questions
- Does greedy forward selection always discover the globally optimal subset of k towns?
- How should the pipeline change when weather stations drop out or leave missing calendar dates?
- How can the O(1) streaming slope adapt if the true relationship drifts gradually over time?
- Under what physical or statistical conditions is omitting the intercept justified for temperature series?
Similar questions
- End-to-End Residential Property Valuation Modeling
- OLS Subset Selection for NYC Daily Temperatures
- 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
- OLS Subset Selection for NYC Daily Temperatures 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