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

Back to Questions

269. Autocorrelation Function

easy
GeneralGeneral
senior

Compute the autocorrelation function (ACF) for a time series to measure how similar the series is to a lagged version of itself. You’ll implement a simple, beginner-friendly ACF that returns correlations for lags from 0 up to a given maximum lag.

The autocorrelation at lag (k) is defined as:

ρ(k)=t=0nk1(xtμ)(xt+kμ)t=0n1(xtμ)2\rho(k)=\frac{\sum_{t=0}^{n-k-1}(x_t-\mu)(x_{t+k}-\mu)}{\sum_{t=0}^{n-1}(x_t-\mu)^2}

Requirements

Implement the function

python

Rules:

  • Return ACF values for all integer lags k = 0, 1, ..., max_lag.
  • Use the same mean mu computed from the full series x for every lag.
  • Use the denominator (\sum_{t=0}^{n-1}(x_t-\mu)^2) (so rho(0) should be 1.0).
  • Do not call any prebuilt autocorrelation/correlation utilities (e.g., np.correlate or pd.Series.autocorr).
  • Use vectorized NumPy operations (e.g. slicing) for calculating the sums, rather than Python loops over time steps.
  • Return the result as a NumPy array.

Example

python

Output:

python
Input Signature
ArgumentType
xnp.ndarray
max_lagint
Output Signature
Return NameType
valuenp.ndarray

Constraints

  • Return NumPy array length max_lag+1

  • No np.correlate or built-in ACF utilities

  • Use vectorized operations

Hint 1

Compute a single mean mu = np.mean(x) from the full series, and reuse it for every lag.

Hint 2

Precompute the deviatiations diff = x - mu.

Hint 3

Compute the denominator denom = np.sum(diff**2) once.

Hint 4

For each lag k, use slicing diff[:-k] and diff[k:] to vectorize the numerator calculation.

Roles
ML Engineer
AI Engineer
Data Scientist
Quantitative Analyst
Companies
GeneralGeneral
Levels
senior
entry
Tags
time-series
autocorrelation
numerical-methods
loops-and-complexity
40 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