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 y is non-constant (SST > 0).
  • Valid inputs satisfy 0.0 <= r2_x1 <= 1.0 and 0.0 <= r2_x2 <= 1.0; raise ValueError otherwise.
  • Return [min_r2, max_r2] as a two-element list of floats.

Step-by-step walkthrough

  1. 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 n training records, each including an intercept b0:

    1. y ~ 1 + x1, achieving training score r2_x1
    2. y ~ 1 + x2, achieving training score r2_x2
    3. y ~ 1 + x1 + x2 (the joint two-feature model)

    Here R-squared (R^2) measures the fraction of variation around mean(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 / SST
    

    With non-constant y (SST > 0) and inputs r2_x1 and r2_x2 (such as 0.16 and 0.36), we want to return [lower_bound, upper_bound]: the tightest minimum and maximum R^2 values that y ~ 1 + x1 + x2 can achieve across all datasets matching those univariate scores.

  2. 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)^2 is non-negative, so SSE >= 0. Dividing by SST > 0 and subtracting from 1 ensures R^2 <= 1, hitting 1 only when SSE = 0 (exact reconstruction on every row).
    • Why R^2 >= 0: Because b0 is an allowed parameter, setting b0 = mean(y) and setting every slope to 0 is always a valid candidate line, producing SSE = SST. Since OLS minimizes SSE over all candidate parameters, the optimal fit obeys SSE <= SST, giving 1 - SSE / SST >= 0.

    Moreover, an intercept forces residuals y_i - y_hat_i to sum to 0 and be perpendicular (zero dot product) to the centered predictions y_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 x with an intercept, R^2(y ~ 1 + x) equals corr(y, x)^2, the squared sample correlation between y and x.

  3. Why the naive guess (adding the two scores) fails

    Given r2_x1 = 0.16 and r2_x2 = 0.36, a tempting first guess is 0.16 + 0.36 = 0.52.

    Adding univariate scores holds only when x1 and x2 are uncorrelated with one another (corr(x1, x2) = 0). Because nothing fixes the correlation between x1 and x2:

    • Heavy redundancy between x1 and x2 makes them explain the same part of y, pulling the joint score down below 0.52.
    • Shared noise of opposite sign lets a linear combination cancel that noise, pushing the joint score above 0.52 — all the way to 1.0.
    • Notice too that for inputs like 0.60 and 0.70, their sum 1.30 exceeds the hard ceiling 1.0.
  4. Lower bound: adding a predictor never hurts in-sample

    In y_hat = b0 + b1 * x1 + b2 * x2, OLS is free to pick b2 = 0 (matching the best y ~ 1 + x1 fit) or b1 = 0 (matching the best y ~ 1 + x2 fit):

    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_x2
    

    Together 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. For r2_x1 = 0.16 and r2_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.16
    

    Here x1 overlaps y solely along e1, which x2 already provides without e3 noise. Adding x1 explains zero extra variation, achieving R^2(joint) = 0.36 = max(0.16, 0.36).

  5. Upper bound: noise cancellation can reach 1.0

    Even when both univariate scores are small, can y ~ 1 + x1 + x2 reach R^2 = 1.0?

    Consider a centered unit-variance target y and centered unit-variance noise z orthogonal to y:

    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.00
    

    Feature x1 acts as a suppressor variable: uncorrelated with y by itself, yet able to strip the exact disturbance z out of x2.

    The same construction works for r2_x1 = 0.16 and r2_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)) * y
    

    Rescaling recovers y with zero error (R^2 = 1.0). That rescaling fails only when sqrt(r2_x1 * (1 - r2_x2)) + sqrt(r2_x2 * (1 - r2_x1)) == 0, which for r2_x1, r2_x2 < 1 happens if and only if r2_x1 == 0 and r2_x2 == 0:

    • Both zero (r2_x1 == 0 and r2_x2 == 0): Centered y has zero dot product with centered x1 and with centered x2. By linearity, centered y also has zero dot product with every combination b1 * x1 + b2 * x2, locking the joint score at [0.0, 0.0].
    • Either score equals 1.0: One predictor already fits y without error, collapsing the interval to [1.0, 1.0].
    • Every intermediate value is reachable: Continuously rotating x1's noise component from e3 toward -z sweeps R^2(joint) continuously across [max(r2_x1, r2_x2), 1.0].
  6. 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 ~ x1 forced through the origin): Predicting the flat constant mean(y) is no longer permitted unless mean(y) = 0. Under centered SST, a line through the origin can produce SSE > SST and yield a negative R^2 (though some libraries switch to uncentered sum(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^2 below max(r2_x1, r2_x2) or even below 0.
    • Mismatched row subsets: If missing entries in x2 cause y ~ 1 + x1 + x2 to drop rows that were kept in y ~ 1 + x1, the models no longer share the same observations or SST.
  7. 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]
    
  8. 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: Set x1 = z = [0, 0, 1, -1] and x2 = 0.8 * y + 0.6 * z = [0.8, -0.8, 0.6, -0.6]. Individually, r2_x1 = 0.0 and r2_x2 = 0.64. Together, 1.25 * x2 - 0.75 * x1 = [1, -1, 0, 0] = y fits every row with zero residual (the leftover error y_i - y_hat_i on row i), reaching R^2 = 1.0 and matching [max(0.0, 0.64), 1.0] = [0.64, 1.0].
  • Redundancy hits the lower bound: Keep y = [1, -1, 0, 0], set x2 = 0.7 * y + sqrt(0.51) * z (r2_x2 = 0.49), and set x1 = x2 (r2_x1 = 0.49). Because x1 adds zero new information beyond x2, the joint R^2 stays at 0.49 = max(0.49, 0.49).
  • Both zero stays zero: When both r2_x1 = 0.0 and r2_x2 = 0.0, neither column correlates with y, so no linear combination b1 * x1 + b2 * x2 correlates with y either, pinning the range at [0.0, 0.0].

Complexity

  • Time: O(1). We run two range checks, one equality check against 0.0, and one max(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)): Centered y is orthogonal (has zero dot product, meaning zero linear correlation) to both centered x1 and centered x2, 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 with y on 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, forcing lower_bound = 1.0 and returning [1.0, 1.0].
  • Identical positive scores (e.g., (0.49, 0.49)): Returns [0.49, 1.0]. Choosing x1 = x2 attains 0.49 (individual slopes are non-unique under exact collinearity, whereas fitted values y_hat and R^2 remain unique).
  • Tiny positive scores (e.g., (0.001, 0.002)): Returns [0.002, 1.0]; any nonzero signal component can be rescaled to y once opposing noise cancels.
  • Very small row counts (n <= 3): Centering n observations leaves n - 1 geometric dimensions. At n = 3 (2 centered dimensions), any two linearly independent columns span the entire centered space (R^2 = 1.0); attaining the lower bound with distinct predictors requires n >= 4.
  • Out-of-bounds inputs (< 0 or > 1): Impossible for in-sample OLS with an intercept and non-constant y; our implementation raises ValueError.

Common mistakes

  • Summing the two scores (r2_x1 + r2_x2). Explained fractions add only when corr(x1, x2) == 0. Correlated predictors can pull the joint fit down to max(r2_x1, r2_x2) or lift it to 1.0 (and for 0.60 and 0.70, 1.30 exceeds 1.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 to y.
  • Assuming r2_x1 == 0 makes x1 useless. 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^2 with adjusted or test-set R^2. Unadjusted training R^2 on fixed rows never drops when adding columns, unlike adjusted R-squared (which penalizes extra parameters for consumed degrees of freedom) or out-of-sample R^2.
  • Comparing fits across inconsistent row subsets. Dropping missing values separately per regression changes the active rows and SST, breaking the max(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 y with a huge shared disturbance z of opposite sign — for instance, x1 = 0.4 * y + sqrt(0.84) * z (r2_x1 = 0.16) and x2 = 0.6 * y - 0.8 * z (r2_x2 = 0.36). Forming 0.8 * x1 + sqrt(0.84) * x2 cancels z identically and leaves a pure multiple of y (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 * x1 is also reachable by y_hat = b0 + b1 * x1 + b2 * x2 simply by setting b2 = 0. Because OLS minimizes SSE over a strictly larger family of linear combinations on the exact same observations, the minimized SSE can only stay equal or decrease, so 1 - SSE / SST with fixed SST can never decrease. Only metrics that penalize model complexity (like adjusted R^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 / SST is undefined (0 / 0 or division by zero) whenever SST = 0, meaning every scored row has the exact same target value y_i. Under centered SST, R^2 becomes negative whenever SSE > SST — that is, when the model's predictions have larger squared error than predicting the constant sample average mean(y). This routinely occurs when scoring a model out of sample on unseen test data, or when fitting OLS without an intercept (y ~ x forced through the origin) on data whose mean is far from zero (note that some statistical packages switch no-intercept regressions to uncentered SST = sum(y_i^2) to keep numbers in [0, 1], making them incomparable to models with an intercept).

Follow-up questions

Similar questions

More Voleon interview questions

All 34 Voleon questions →