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

Back to Questions

229. Difference transformation

easy
GeneralGeneral
senior

Implement a difference transformation for a time series, which converts raw values into changes between consecutive time steps. The first-order difference is defined as:

Δxt=xt−xt−1\Delta x_t = x_t - x_{t-1}

Requirements

Implement the function

python

Rules:

  • Apply differencing order times (e.g., order=2 means difference the series, then difference the result).
  • Return a NumPy array.
  • Do not use any prebuilt differencing utilities (e.g., pandas .diff() or np.diff). Use array slicing.
  • Keep the output length consistent with differencing (each differencing step reduces length by 1).
  • Use only NumPy and built-in libraries.

Example

python

Output:

python
Input Signature
ArgumentType
orderint
seriesnp.ndarray
Output Signature
Return NameType
valuenp.ndarray

Constraints

  • Return NumPy array.

  • No pandas/.diff or np.diff; use array slicing.

  • Each order reduces length by 1.

Hint 1

Use current = series.astype(float) to ensure you can perform subtraction on float arrays.

Hint 2

Use array slicing for efficiency: current[1:] - current[:-1] computes differences for the whole array at once.

Hint 3

Loop order times, updating current with the sliced difference result each time.

Roles
ML Engineer
AI Engineer
Data Scientist
Quantitative Analyst
Companies
GeneralGeneral
Levels
senior
entry
Tags
time-series
differencing
iterative-transform
numpy
50 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