Walk-Forward Cross-Validation Splits

Easy
~15 min
code completion

Walk-Forward Cross-Validation Splits

For time-series data, standard k-fold CV is invalid — you cannot train on future data and evaluate on the past. Walk-forward validation (expanding-window CV) respects temporal order:

  • Start with an initial window of window_size timesteps for training
  • Predict the next step timesteps
  • Expand the training window by step and repeat
  • Each split is a pair [train_end, test_end] — the exclusive end indices of the training and test windows.

    Example: n = 10, window_size = 4, step = 2

    Split 1: train = [0, 4),  test = [4, 6)   → [4, 6]
    Split 2: train = [0, 6),  test = [6, 8)   → [6, 8]
    Split 3: train = [0, 8),  test = [8, 10)  → [8, 10]

    Include all complete splits where test_end <= n.

    Your task:

    Implement walkforward_splits(n, window_size, step) that returns a list of [train_end, test_end] pairs.

    Example Tests

    10 timesteps, window=4, step=2 produces 3 splits

    Input: {"n":10,"step":2,"window_size":4}

    Expected: [[4,6],[6,8],[8,10]]

    Only one complete split fits before running out of data

    Input: {"n":8,"step":3,"window_size":5}

    Expected: [[5,8]]

    12 timesteps split into 2 equal non-overlapping windows

    Input: {"n":12,"step":4,"window_size":4}

    Expected: [[4,8],[8,12]]

    Sign in to solve this problem

    You can read the full problem statement above. Create a free account to run code in the browser, submit solutions, and track your progress.