Joint OLS R-Squared Bounds from Single-Feature Scores
Medium · Statistics & Math · Quantitative Researcher · Technical Screen
Problem Statement
Suppose you observe a target vector y with positive sample variance alongside two numerical feature columns x1 and x2 measured across the exact same n training records. Every linear model includes a constant intercept term and is fitted by ordinary least squares (OLS), minimizing the residual sum of squares SSE = sum((y_i - y_hat_i)^2). Goodness of fit on the training sample is evaluated with the standard centered coefficient of determination:
SST = sum((y_i - mean(y))^2)
R^2 = 1 - SSE / SST
You are given only two summary numbers:
- r2_x1: the training R^2 achieved by the single-feature regression y ~ 1 + x1.
- r2_x2: the training R^2 achieved by the single-feature regression y ~ 1 + x2.
Nothing is specified about the sample correlation between x1 and x2, and n may be arbitrarily large. Implement combined_ols_r2_range(r2_x1: float, r2_x2: float) -> List[float] to return [min_r2, max_r2], the tightest lower and upper bounds on the training R^2 that the joint regression y ~ 1 + x1 + x2 can attain over all datasets compatible with r2_x1 and r2_x2.
If either input lies outside the valid range [0.0, 1.0] for an in-sample OLS fit with an intercept, raise a ValueError.
Examples
Example 1
Input: r2_x1 = 0.16, r2_x2 = 0.36
Output: [0.36, 1.0]
Walk-through: By setting the weight on x1 to zero, the bivariate fit already achieves 0.36, and if x1 only shares signal with y through x2, the joint score stays at 0.36. At the opposite extreme, x1 and x2 may contain opposite-sign copies of an unobserved disturbance that cancel out completely in a linear combination, recovering y without error (1.0).
Example 2
Input: r2_x1 = 0.0, r2_x2 = 0.64
Output: [0.64, 1.0]
Walk-through: Although x1 alone has zero linear correlation with y, x1 can isolate the exact noise term contaminating x2. Subtracting a multiple of x1 from x2 removes all error and pushes the joint R^2 to 1.0, while redundant or independent noise leaves it at 0.64.
Example 3
Input: r2_x1 = 0.49, r2_x2 = 0.49
Output: [0.49, 1.0]
Walk-through: When x1 and x2 are identical columns, combining them explains the exact same 49% of variance as either predictor alone; when their residual components oppose each other, a linear combination reconstructs y with R^2 = 1.0.
Example 4
Input: r2_x1 = 0.85, r2_x2 = 1.0
Output: [1.0, 1.0]
Walk-through: Feature x2 already reproduces y with zero residual error on every training row, pinning both the minimum and maximum achievable joint R^2 at 1.0.
Constraints
- Both univariate and bivariate models include an intercept term and are fitted and scored on the identical training rows.
- The target
yis non-constant (SST > 0). - Valid inputs satisfy
0.0 <= r2_x1 <= 1.0and0.0 <= r2_x2 <= 1.0; raiseValueErrorotherwise. - Return
[min_r2, max_r2]as a two-element list of floats.
Step-by-step walkthrough
Restate the problem and core terms
We fit three ordinary least squares (OLS) regressions — linear models chosen to minimize the sum of squared prediction errors — across the exact same
ntraining records, each including an interceptb0:y ~ 1 + x1, achieving training scorer2_x1y ~ 1 + x2, achieving training scorer2_x2y ~ 1 + x1 + x2(the joint two-feature model)
Here R-squared (
R^2) measures the fraction of variation aroundmean(y)captured by the fitted predictions:SSE = sum((y_i - y_hat_i)^2) <-- Sum of Squared Errors remaining after fitting SST = sum((y_i - mean(y))^2) <-- Total Sum of Squares around the sample mean of y R^2 = 1 - SSE / SSTWith non-constant
y(SST > 0) and inputsr2_x1andr2_x2(such as0.16and0.36), we want to return[lower_bound, upper_bound]: the tightest minimum and maximumR^2values thaty ~ 1 + x1 + x2can achieve across all datasets matching those univariate scores.Why in-sample R-squared with an intercept lies in [0, 1]
First let us verify why every training OLS fit that includes an intercept satisfies
0 <= R^2 <= 1:- Why
R^2 <= 1: Every squared residual(y_i - y_hat_i)^2is non-negative, soSSE >= 0. Dividing bySST > 0and subtracting from1ensuresR^2 <= 1, hitting1only whenSSE = 0(exact reconstruction on every row). - Why
R^2 >= 0: Becauseb0is an allowed parameter, settingb0 = mean(y)and setting every slope to0is always a valid candidate line, producingSSE = SST. Since OLS minimizesSSEover all candidate parameters, the optimal fit obeysSSE <= SST, giving1 - SSE / SST >= 0.
Moreover, an intercept forces residuals
y_i - y_hat_ito sum to0and be perpendicular (zero dot product) to the centered predictionsy_hat_i - mean(y), splitting variation cleanly:SST = SSR + SSE where SSR = sum((y_hat_i - mean(y))^2) R^2 = SSR / SST (explained variation divided by total variation)For one feature
xwith an intercept,R^2(y ~ 1 + x)equalscorr(y, x)^2, the squared sample correlation betweenyandx.- Why
Why the naive guess (adding the two scores) fails
Given
r2_x1 = 0.16andr2_x2 = 0.36, a tempting first guess is0.16 + 0.36 = 0.52.Adding univariate scores holds only when
x1andx2are uncorrelated with one another (corr(x1, x2) = 0). Because nothing fixes the correlation betweenx1andx2:- Heavy redundancy between
x1andx2makes them explain the same part ofy, pulling the joint score down below0.52. - Shared noise of opposite sign lets a linear combination cancel that noise, pushing the joint score above
0.52— all the way to1.0. - Notice too that for inputs like
0.60and0.70, their sum1.30exceeds the hard ceiling1.0.
- Heavy redundancy between
Lower bound: adding a predictor never hurts in-sample
In
y_hat = b0 + b1 * x1 + b2 * x2, OLS is free to pickb2 = 0(matching the besty ~ 1 + x1fit) orb1 = 0(matching the besty ~ 1 + x2fit):SSE(y ~ 1 + x1 + x2) <= SSE(y ~ 1 + x1) --> R^2(joint) >= r2_x1 SSE(y ~ 1 + x1 + x2) <= SSE(y ~ 1 + x2) --> R^2(joint) >= r2_x2Together these give
R^2(joint) >= max(r2_x1, r2_x2).To verify that
max(r2_x1, r2_x2)is actually reachable, make the weaker feature a noisy copy of the stronger one. Forr2_x1 = 0.16andr2_x2 = 0.36:Let e1, e2, e3 be centered, unit-length, mutually orthogonal columns (requiring >= 4 rows): x2 = e1 y = 0.6 * e1 + 0.8 * e2 --> corr(y, x2)^2 = 0.6^2 = 0.36 x1 = (2/3) * e1 + (sqrt(5)/3) * e3 --> corr(y, x1)^2 = (0.6 * 2/3)^2 = 0.4^2 = 0.16Here
x1overlapsysolely alonge1, whichx2already provides withoute3noise. Addingx1explains zero extra variation, achievingR^2(joint) = 0.36 = max(0.16, 0.36).Upper bound: noise cancellation can reach 1.0
Even when both univariate scores are small, can
y ~ 1 + x1 + x2reachR^2 = 1.0?Consider a centered unit-variance target
yand centered unit-variance noisezorthogonal toy:x1 = z --> pure noise alone: R^2(y ~ 1 + x1) = 0.00 x2 = 0.8 * y + 0.6 * z --> signal mixed with z: R^2(y ~ 1 + x2) = 0.64 (x2 - 0.6 * x1) / 0.8 --> noise z cancels out: R^2(y ~ 1 + x1 + x2) = 1.00Feature
x1acts as a suppressor variable: uncorrelated withyby itself, yet able to strip the exact disturbancezout ofx2.The same construction works for
r2_x1 = 0.16andr2_x2 = 0.36(or any pair in[0, 1)where at least one score is positive):x1 = 0.4 * y + sqrt(0.84) * z --> corr(y, x1)^2 = 0.16 x2 = 0.6 * y - 0.8 * z --> corr(y, x2)^2 = 0.36 Combine to eliminate z: 0.8 * x1 + sqrt(0.84) * x2 = (0.32 + 0.6 * sqrt(0.84)) * y + (0.8 * sqrt(0.84) - 0.8 * sqrt(0.84)) * z = (0.32 + 0.6 * sqrt(0.84)) * yRescaling recovers
ywith zero error (R^2 = 1.0). That rescaling fails only whensqrt(r2_x1 * (1 - r2_x2)) + sqrt(r2_x2 * (1 - r2_x1)) == 0, which forr2_x1, r2_x2 < 1happens if and only ifr2_x1 == 0andr2_x2 == 0:- Both zero (
r2_x1 == 0andr2_x2 == 0): Centeredyhas zero dot product with centeredx1and with centeredx2. By linearity, centeredyalso has zero dot product with every combinationb1 * x1 + b2 * x2, locking the joint score at[0.0, 0.0]. - Either score equals
1.0: One predictor already fitsywithout error, collapsing the interval to[1.0, 1.0]. - Every intermediate value is reachable: Continuously rotating
x1's noise component frome3toward-zsweepsR^2(joint)continuously across[max(r2_x1, r2_x2), 1.0].
- Both zero (
What changes when standard assumptions are relaxed
It also helps in interviews to note what happens outside standard in-sample OLS with an intercept:
- Dropping the intercept (
y ~ x1forced through the origin): Predicting the flat constantmean(y)is no longer permitted unlessmean(y) = 0. Under centeredSST, a line through the origin can produceSSE > SSTand yield a negativeR^2(though some libraries switch to uncenteredsum(y_i^2)in no-intercept mode). - Held-out test evaluation: Coefficients fitted on training rows can overfit noise and produce arbitrarily large errors on unseen test data, pushing out-of-sample
R^2belowmax(r2_x1, r2_x2)or even below0. - Mismatched row subsets: If missing entries in
x2causey ~ 1 + x1 + x2to drop rows that were kept iny ~ 1 + x1, the models no longer share the same observations orSST.
- Dropping the intercept (
Trace the examples
Let us check our rule across the four examples from the statement plus the all-zero boundary:
Input (r2_x1, r2_x2) Both zero? Lower = max(r2_x1, r2_x2) Upper Returned range -------------------- ---------- ------------------------- ----- -------------- (0.16, 0.36) No 0.36 1.0 [0.36, 1.0] (0.0, 0.64) No 0.64 1.0 [0.64, 1.0] (0.49, 0.49) No 0.49 (e.g. when x1 == x2) 1.0 [0.49, 1.0] (0.85, 1.0) No 1.0 (x2 fits y exactly) 1.0 [1.0, 1.0] (0.0, 0.0) Yes 0.0 0.0 [0.0, 0.0]Complete solution
Putting input validation, the
(0.0, 0.0)corner case, and[max(r2_x1, r2_x2), 1.0]together gives the complete implementation:from typing import Any, Dict, List, Optional, Set, Tuple def combined_ols_r2_range(r2_x1: float, r2_x2: float) -> List[float]: """Return [min_r2, max_r2] for in-sample OLS y ~ x1 + x2 (with intercept), given the individual R-squared scores of y ~ x1 and y ~ x2 on the same rows.""" # Phase 1: Validate inputs. With an intercept and nonconstant y, in-sample R^2 # always lies in [0, 1] because 0 <= SSE <= SST. for score in (r2_x1, r2_x2): if score < 0.0 or score > 1.0: raise ValueError("in-sample R-squared with an intercept must lie in [0, 1]") # Phase 2: Handle the all-zero special case. # R^2 == 0 means centered y has zero dot product with that centered predictor. # If both dot products are zero, centered y also has zero dot product with every # linear mix b1 * x1 + b2 * x2, so the joint model can only predict mean(y). if r2_x1 == 0.0 and r2_x2 == 0.0: return [0.0, 0.0] # Phase 3: Compute general bounds [lower_bound, upper_bound]. # Lower bound: setting one slope to 0 reproduces the better single-predictor fit, # so OLS can never end up with larger training error (smaller R^2) than max(r2_x1, r2_x2). lower_bound = float(max(r2_x1, r2_x2)) # Upper bound: when at least one predictor carries signal (score > 0), x1 and x2 can # carry opposite-sign copies of the same noise so a linear combination cancels the # noise completely and reconstructs y with zero error (R^2 = 1.0). upper_bound = 1.0 return [lower_bound, upper_bound]✅ Submit now — all tests should pass.
Intuition & how it works
Think of x1 and x2 as two witnesses describing an outcome y, and ordinary least squares (OLS) — a regression method that chooses weights to minimize total squared prediction error — as an investigator combining their clues. Each univariate R-squared (R^2 = 1 - SSE / SST, the share of squared variation around mean(y) captured by the fitted predictions) reports how accurately one witness predicts y alone when an intercept (a constant baseline offset b0) is included. Because the bivariate model y ~ 1 + x1 + x2 can always assign a weight of 0 to either column, its training score can never fall below the better individual witness (max(r2_x1, r2_x2)). At the upper end, whenever at least one witness carries any genuine signal (max(r2_x1, r2_x2) > 0), the two columns may contain opposite-sign copies of the same background noise so that combining them cancels the noise completely and reconstructs y with 100% accuracy (R^2 = 1.0).
A tempting naive shortcut is to add the two univariate scores (0.16 + 0.36 = 0.52), treating explained fractions as independent pieces. That breaks down because we do not know the correlation (a measure from -1 to 1 of how strongly two variables move together linearly) between x1 and x2. If x1 only repeats signal already inside x2, the joint score stays stuck at 0.36; if x1 cancels x2's disturbance, the joint score jumps to 1.0.
Trace a concrete 4-row dataset with y = [1, -1, 0, 0] (mean 0, SST = 2) and orthogonal noise z = [0, 0, 1, -1]:
- Noise cancellation hits the upper bound
1.0: Setx1 = z = [0, 0, 1, -1]andx2 = 0.8 * y + 0.6 * z = [0.8, -0.8, 0.6, -0.6]. Individually,r2_x1 = 0.0andr2_x2 = 0.64. Together,1.25 * x2 - 0.75 * x1 = [1, -1, 0, 0] = yfits every row with zero residual (the leftover errory_i - y_hat_ion rowi), reachingR^2 = 1.0and matching[max(0.0, 0.64), 1.0] = [0.64, 1.0]. - Redundancy hits the lower bound: Keep
y = [1, -1, 0, 0], setx2 = 0.7 * y + sqrt(0.51) * z(r2_x2 = 0.49), and setx1 = x2(r2_x1 = 0.49). Becausex1adds zero new information beyondx2, the jointR^2stays at0.49 = max(0.49, 0.49). - Both zero stays zero: When both
r2_x1 = 0.0andr2_x2 = 0.0, neither column correlates withy, so no linear combinationb1 * x1 + b2 * x2correlates withyeither, pinning the range at[0.0, 0.0].
Complexity
- Time: O(1). We run two range checks, one equality check against
0.0, and onemax(r2_x1, r2_x2)call — a small constant number of scalar operations independent of dataset size. - Space: O(1). We allocate only two scalar bounds (
lower_bound,upper_bound) and return a two-element list.
Edge cases
- Both scores equal
0((0.0, 0.0)): Centeredyis orthogonal (has zero dot product, meaning zero linear correlation) to both centeredx1and centeredx2, so it remains orthogonal to every linear combination of them; the range collapses to[0.0, 0.0]. - One score
0, the other positive (e.g.,(0.0, 0.64)): Returns[0.64, 1.0], because a zero-correlation column can serve as a suppressor variable (a feature uncorrelated withyon its own that boosts joint accuracy by subtracting noise out of another predictor). - Either score equals
1(e.g.,(0.85, 1.0)): One feature already achieves zero training error alone, forcinglower_bound = 1.0and returning[1.0, 1.0]. - Identical positive scores (e.g.,
(0.49, 0.49)): Returns[0.49, 1.0]. Choosingx1 = x2attains0.49(individual slopes are non-unique under exact collinearity, whereas fitted valuesy_hatandR^2remain unique). - Tiny positive scores (e.g.,
(0.001, 0.002)): Returns[0.002, 1.0]; any nonzero signal component can be rescaled toyonce opposing noise cancels. - Very small row counts (
n <= 3): Centeringnobservations leavesn - 1geometric dimensions. Atn = 3(2centered dimensions), any two linearly independent columns span the entire centered space (R^2 = 1.0); attaining the lower bound with distinct predictors requiresn >= 4. - Out-of-bounds inputs (
< 0or> 1): Impossible for in-sample OLS with an intercept and non-constanty; our implementation raisesValueError.
Common mistakes
- Summing the two scores (
r2_x1 + r2_x2). Explained fractions add only whencorr(x1, x2) == 0. Correlated predictors can pull the joint fit down tomax(r2_x1, r2_x2)or lift it to1.0(and for0.60and0.70,1.30exceeds1.0). - Missing the
(0.0, 0.0)corner case. Returning[max(r2_x1, r2_x2), 1.0]blindly yields[0.0, 1.0]for(0.0, 0.0), overlooking that two orthogonal vectors span a plane completely orthogonal toy. - Assuming
r2_x1 == 0makesx1useless. Ignoring suppressor noise cancellation leads candidates to guess[0.64, 0.64]on(0.0, 0.64)instead of[0.64, 1.0]. - Confusing ordinary
R^2with adjusted or test-setR^2. Unadjusted trainingR^2on fixed rows never drops when adding columns, unlike adjusted R-squared (which penalizes extra parameters for consumed degrees of freedom) or out-of-sampleR^2. - Comparing fits across inconsistent row subsets. Dropping missing values separately per regression changes the active rows and
SST, breaking themax(r2_x1, r2_x2)floor.
Follow-up questions
- How is it possible for a two-feature regression to achieve a perfect fit when both individual features have very low R-squared? As long as at least one univariate score is strictly positive, both features can blend a tiny fraction of the true target
ywith a huge shared disturbancezof opposite sign — for instance,x1 = 0.4 * y + sqrt(0.84) * z(r2_x1 = 0.16) andx2 = 0.6 * y - 0.8 * z(r2_x2 = 0.36). Forming0.8 * x1 + sqrt(0.84) * x2cancelszidentically and leaves a pure multiple ofy(R^2 = 1.0). In real modeling workflows (such as relative-value spreads in finance), this corresponds to extracting a clean spread from two noisy, heavily correlated series, which produces large opposite-sign slopes that must be regularized or validated out of sample. - Why can't adding an extra feature ever lower the unadjusted R-squared on the training sample? Every prediction vector reachable by
y_hat = b0 + b1 * x1is also reachable byy_hat = b0 + b1 * x1 + b2 * x2simply by settingb2 = 0. Because OLS minimizesSSEover a strictly larger family of linear combinations on the exact same observations, the minimizedSSEcan only stay equal or decrease, so1 - SSE / SSTwith fixedSSTcan never decrease. Only metrics that penalize model complexity (like adjustedR^2) or evaluate on held-out test rows can fall when a noisy column is added. - When does the standard R-squared formula produce a negative number or fail to be defined at all?
R^2 = 1 - SSE / SSTis undefined (0 / 0or division by zero) wheneverSST = 0, meaning every scored row has the exact same target valuey_i. Under centeredSST,R^2becomes negative wheneverSSE > SST— that is, when the model's predictions have larger squared error than predicting the constant sample averagemean(y). This routinely occurs when scoring a model out of sample on unseen test data, or when fitting OLS without an intercept (y ~ xforced through the origin) on data whose mean is far from zero (note that some statistical packages switch no-intercept regressions to uncenteredSST = sum(y_i^2)to keep numbers in[0, 1], making them incomparable to models with an intercept).
Follow-up questions
- How is it possible for a two-feature regression to achieve a perfect fit when both individual features have very low R-squared?
- Why can't adding an extra feature ever lower the unadjusted R-squared on the training sample?
- When does the standard R-squared formula produce a negative number or fail to be defined at all?
Similar questions
- A/B Inference on Zero-Inflated Heavy-Tailed Revenue
- Diagnosing OLS Violations in Count Regression
- Zero Printed P-Values and Bootstrap Inference for Regression Slopes
- Markov Chains, Rotated OLS Estimators, and Parallel Coin Stopping Times
- Ring Bit Toggles Under Stepping Markers
- Greedy Collinearity Feature Filter and Atomic CSV Cleaner
More Voleon interview questions
- Greedy Collinearity Feature Filter and Atomic CSV Cleaner Easy
- Auditing, Tuning, and Serving a Forecasting Pipeline Medium
- Queen Line-of-Sight Queries With Obstacles Medium Pro
- Regression Pipeline Design for Skewed Customer Revenue Hard Pro
- Sparse Matrix Arithmetic with Shape Validation Medium Pro
- Diagnosing Train and Test Loss Across Regularization and Sample Size Medium Pro
- Keep Words with Non-Unique Anagram Signatures Medium Pro
- Limit Order Book and Participation-Rate Execution Simulator Medium Pro
- Markov Chains, Rotated OLS Estimators, and Parallel Coin Stopping Times Easy Pro
- Verify Binary Strings Under a Prefix Grammar Medium Pro