Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Implement Simple Linear Regression

EasyPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Implement Simple Linear Regression. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

At Lyft, a small analytics tool needs a basic linear regression function without using external ML libraries. Given paired numeric observations, compute the best-fit line y = mx + b using ordinary least squares.

Task

Write a function that takes two arrays, x_values and y_values, and returns the slope and intercept of the regression line.

Formal Specification

  • Input:
    • x_values: list of numbers of length n
    • y_values: list of numbers of length n
  • Output:
    • A list [slope, intercept]
  • If the input lengths differ, contain fewer than 2 points, or all x_values are identical, return [].

Use the formulas:

  • slope = sum((xi - mean_x) * (yi - mean_y)) / sum((xi - mean_x)^2)
  • intercept = mean_y - slope * mean_x

Constraints

  • 2 <= n <= 10^5
  • x_values.length == y_values.length for valid input
  • -10^6 <= x_values[i], y_values[i] <= 10^6
  • Return [] for invalid input or when all x_values are identical
  • Do not use external regression or machine learning libraries

Function Signature

def linear_regression(x_values, y_values):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output