Time Series Cross-Validation Splits With Gap
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `time_series_split(n_samples, n_splits, test_size, gap=0, window="expanding", train_size=None)` returning a list of `n_splits` `(train, test)` tuples of ascending integer `np.ndarray`s.
Fold `i` (0-based) tests `[s_i, s_i + test_size)` with `s_i = n_samples - (n_splits - i) * test_size`, and its training window ends (exclusive) at `s_i - gap`. With `window="expanding"` the fold trains on `[0, s_i - gap)`. With `window="sliding"` it trains on `[s_i - gap - train_size, s_i - gap)`.
Example:
```python
time_series_split(10, 3, 2, gap=1)
# [([0, 1, 2], [4, 5]),
# ([0, 1, 2, 3, 4], [6, 7]),
# ([0, 1, 2, 3, 4, 5, 6], [8, 9])]
```
```hint Before the error checks
Write the training end of fold `i` as a formula in `i` before you write the "not enough samples" checks.
```
```hint Off-by-one at the gap
Write every window as a half-open interval before you code it, then trace the example by hand. Fold 0 should leave exactly one index (3) out of both sets.
```
### Constraints & Assumptions
- `n_samples`, `n_splits`, `test_size` and `gap` must be integers (not `bool`), else `ValueError`.
- Raise `ValueError` if `n_splits < 1`, `test_size < 1`, `gap < 0`, or `window` is not `"expanding"` or `"sliding"`.
- `train_size` must be `None` for an expanding window and an integer of at least 1 for a sliding window, else `ValueError`.
- Raise `ValueError` if the first fold's training end is below 1, or, for a sliding window, below `train_size`.
- Expanding output must match scikit-learn's `TimeSeriesSplit(n_splits, test_size=..., gap=...)` for the inputs it accepts.
### What a Strong Answer Covers
- Test blocks anchored to the end of the series and tiled without overlap, using the given start formula.
- Training windows that stop `gap` samples before each test block, for both window types.
- Complete parameter validation, including the `bool` exclusion, the `train_size` rule for each window type, and the feasibility checks.
- Why the feasibility checks only need the first fold, and how the expanding output lines up with scikit-learn.
- Time and memory cost of building the index arrays.
### Follow-up Questions
- How would you handle labels that span multiple time steps (for example 5-day forward returns)?
- What changes if timestamps are irregular or multiple rows share a timestamp?
- How would you tune hyperparameters without leaking from the final evaluation folds?
Overview: Implement forward-chaining time series cross-validation that places test blocks at the end of the series, leaves a gap before each one, and supports expanding or sliding training windows. It tests index arithmetic, input validation and how to avoid look-ahead leakage when evaluating forecasting models.