KatInterview

Simple OLS Linear Regression Fitting

Math & Bit ManipulationAuto-graded · 21 test cases
EasyAuto-gradedMath & Bit Manipulationmatharraysstatistics

Last updated

Compute the slope and intercept for a univariate linear regression model using ordinary least squares.

Given a set of $n$ paired measurements $(x_1, y_1), (x_2, y_2), \dots, (x_n, y_n)$, determine the slope $m$ and y-intercept $c$ for the linear equation

$$\hat{y} = m x + c$$

that minimizes the total squared residual error $\sum_{i=1}^{n} (y_i - \hat{y}_i)^2$.

The closed-form Ordinary Least Squares (OLS) solutions for the slope $m$ and intercept $c$ are defined as:

$$m = \frac{\sum_{i=1}^{n} (x_i - \bar{x})(y_i - \bar{y})}{\sum_{i=1}^{n} (x_i - \bar{x})^2}$$

$$c = \bar{y} - m \bar{x}$$

where $\bar{x}$ and $\bar{y}$ represent the arithmetic means of the inputs $x$ and targets $y$, respectively.

Implement a function that computes and returns these parameters as a list [slope, intercept].

Constraints

  • $2 \le n \le 100,000$
  • $-10^6 \le x[i], y[i] \le 10^6$
  • $x$ contains at least two distinct values (guaranteeing a non-zero denominator).
  • Do not use external machine learning or statistical modeling libraries.
  • Standard double-precision floating-point tolerances apply (absolute/relative error within $10^{-6}$).

Examples

Example 1

Input: linear_regression_ols([1, 2, 3], [2, 4, 6])

Output: [2, 0]

Example 2

Input: linear_regression_ols([0, 1, 2, 3], [1, 3, 2, 5])

Output: [1.1, 1.0999999999999999]

Example 3

Input: linear_regression_ols([5, 5, 10], [1, 3, 2])

Output: [0, 2]

Hints

Hint 1

First, iterate over the arrays to calculate the sample averages for x and y.

Hint 2

In a second pass, sum the products of centered deviations (x[i] - mean_x) * (y[i] - mean_y) for the numerator and (x[i] - mean_x)^2 for the denominator.

Hint 3

Avoid the single-pass raw sum formula (n*sum(x*y) - sum(x)*sum(y)) as it can suffer from catastrophic floating-point cancellation when values are large.