Join Our 5-Week ML/AI Engineer Interview Bootcamp 🚀 led by ML Tech Leads at FAANGs

Back to Questions

25. Lag features

easy
GeneralGeneral
senior

Lag features are a simple way to turn past values in a time series into input features for a model. You’ll build a lagged feature matrix from a 1D sequence so it can be fed into standard ML models.

Requirements

Implement the function

python

Rules:

  • Use the lags exactly as provided (don’t sort them).
  • Only create rows for indices where all lagged values exist (i.e., start at t = max(lags)).
  • Return X and y as NumPy arrays.
  • Do not use pandas or any time-series helper libraries.
  • Keep the implementation in this single function.

Example

python

Output:

python
Input Signature
ArgumentType
lagslist
seriesnp.ndarray
Output Signature
Return NameType
valuetuple

Constraints

  • Return NumPy arrays

  • Do not sort lags; preserve input order

  • Rows start at t = max(lags) only

Hint 1

Compute the first valid index t: you can only build a row when all t - lag indices are non-negative, so start at t = max(lags).

Hint 2

For each valid t in range(max_lag, n), build one row as [series[t - lag] for lag in lags] and append series[t] to y.

Hint 3

If using NumPy slicing for speed: for each lag L, the whole column is s[max_lag - L : n - L]; fill columns in the given lag order.

Roles
ML Engineer
AI Engineer
Companies
GeneralGeneral
Levels
senior
entry
Tags
time-series
feature-engineering
lagged-features
numpy-slicing
34 people are solving this problem
Python LogoPython Editor
Ln 1, Col 1

Input Arguments

Edit values below to test with custom inputs

You need tolog in/sign upto run or submit