Differencing Away a Trend, One Pass at a Time

Time SeriesEasy+10 XP+10

Differencing Away a Trend, One Pass at a Time

Most time-series models assume the series is stationary — that its behaviour doesn't drift over time. A series climbing steadily upward breaks that assumption immediately. Differencing fixes it by modelling the changes instead of the levels.

One pass replaces each value with the difference from the one before it:

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

The first value has no predecessor, so each pass makes the series one shorter.

Task: write difference(series, order) returning the series after differencing it order times.

  • order is 0 or more. At order = 0 the series comes back unchanged.
  • Each pass operates on the output of the previous pass, not on the original. Order 2 is the difference of the differences.
  • Don't round. Integers in, integers out.
  • The result's length is len(series) - order.

What each order removes is worth knowing. First differencing kills a linear trend: a series going up by 5 every step becomes a constant 5. Second differencing kills a quadratic one — the squares 1, 4, 9, 16 become 3, 5, 7 and then the constant 2, 2. That's the d in ARIMA, and almost nobody needs it above 2.

The cost is paid in two places: you lose a data point per pass, and your model now predicts changes rather than values, so you have to add the levels back to get a usable forecast.

Examples

series = [1, 4, 9, 16]
order = 1
returns [3, 5, 7]
series = [1, 4, 9, 16]
order = 2
returns [2, 2]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run