Greedy Group K-Fold Splitter
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Given a 1-D array `groups` (one label per sample) and `n_splits`, implement `assign_group_folds(groups, n_splits)`, which returns each sample's fold index, and `group_k_fold(groups, n_splits)`, which returns a list of `(train_indices, val_indices)` tuples, one per fold in order `0..n_splits-1`. Whole groups go to a single fold.
The functions must meet these requirements:
- Process groups by sample count descending (ties: sorted label ascending, which works for ints and strings).
- Assign each group to the fold with the fewest samples so far (ties: lowest fold index).
- Fold assignments and all index arrays are `int64`, and indices are sorted ascending.
- The validation set of fold `f` is all samples assigned to `f`, and train is every other sample.
- Raise `ValueError` if `groups` is not 1-D, `n_splits` is not an integer (`bool` rejected), `n_splits < 2`, or there are fewer unique groups than `n_splits` (both functions).
Example:
```python
groups = [3, 3, 3, 1, 1, 2, 2, 2, 2, 0, 4]
n_splits = 3
# sizes: 2->4, 3->3, 1->2, 0->1, 4->1
assign_group_folds(groups, 3)
# -> [1, 1, 1, 2, 2, 0, 0, 0, 0, 2, 1]
[val for _, val in group_k_fold(groups, 3)]
# -> [[5, 6, 7, 8], [0, 1, 2, 10], [3, 4, 9]]
```
```hint Tie order between groups
One NumPy call can give you sorted labels, each sample's group position and the group sizes. Check whether the sort you then apply to the sizes keeps equal-size groups in label order.
```
```hint Validation pitfalls
In Python, `True` passes `isinstance(x, int)`, while NumPy integers such as `np.int64(3)` fail it. Order your type checks with both cases in mind.
```
### What a Strong Answer Covers
- All four `ValueError` cases in both functions, including rejecting `bool` and accepting NumPy integer types.
- Group ordering by size descending with sorted-label ties, for integer and string labels.
- Greedy assignment to the lightest fold with the lowest-index tie rule, mapped back from groups to samples.
- `int64` outputs with ascending train and validation indices, and every group on one side of each split only.
- The time complexity of the assignment and of building the splits.
### Follow-up Questions
- How would you add stratification so each fold keeps a similar label distribution?
- Why can a single huge group still cause unbalanced folds, and how would you handle it?
- How would you add optional shuffling while keeping results reproducible?
Overview: Implement a deterministic greedy group k-fold splitter that keeps each group in one fold, processing groups largest first and placing each in the lightest fold. It tests leakage-safe cross-validation, exact tie-breaking, input validation and NumPy indexing.