Simple Linear Regression
Description
Given arrays x and y of equal length, fit a simple linear regression y = slope * x + intercept using ordinary least squares. Return [slope, intercept], each rounded to 4 decimal places. The x values are not all equal.
Examples
[1,2,3,4], [2,4,6,8][2,0]Ordinary least squares divides the covariance of x and y by the variance of x to get the slope 2, then chooses the intercept 0 so the line passes through the means of x and y.
[1,2,3], [1,3,5][2,-1]Ordinary least squares divides the covariance of x and y by the variance of x to get the slope 2, then chooses the intercept -1 so the line passes through the means of x and y.
[0,1,2,3], [1,2,3,4][1,1]Ordinary least squares divides the covariance of x and y by the variance of x to get the slope 1, then chooses the intercept 1 so the line passes through the means of x and y.
Constraints
- •
2 ≤ length ≤ 10⁴ - •
x values are not all identical
Ready to solve this problem?
Practice solo and sharpen your skills for technical interviews.