Skip to main content

Implement k-fold cross-validation without a library: return the train and validation indices for each fold. For example, 10 rows and k = 3 should give validation folds of sizes 4, 3 and 3, and every row should be in a validation fold exactly once.

Coding rounds · Intermediate 2

Short answer

Shuffle the row indices once with a seed and cut them into k nearly equal folds with np.array_split. For fold i, validation is fold i and training is every other fold joined. Train and score k times and report the mean and spread. Building the folds is O(n); the real cost is k model fits.

Deeper answer

Clarify first: how many rows, what k, and should the rows be shuffled? Shuffling is right for independent rows, but wrong for time series, where each fold must train on the past only. Ask about groups too, such as many rows from one customer, which must stay in one fold.

The steps: idx = rng.permutation(n), then folds = np.array_split(idx, k), which handles n not divisible by k by making the first folds one row larger. For fold i, the validation indices are folds[i] and the training indices are the other folds joined with np.concatenate. Fit a new model on the training part each time, score it on the validation part, and report the mean and standard deviation of the k scores.

Test that the validation folds do not overlap and that together they cover every row once. Interviewers watch for leakage: fitting a scaler or selecting features on all rows before the loop. Every step that learns from data must be fitted inside the loop on the training part only.

What a strong answer covers

Answer it out loud in the mock interview about 2.5 min

Follow-ups to expect

Common mistakes

Learn it

Cross-validation and leakage

Practice Coding rounds questions

More on this topic

Today's AI turns are used

Lessons, roadmaps, videos, practice cards and the code playground stay free with your account, with no limit.