Validation Split Algorithms
Thirty original Python problems on grouped and stratified splits, time and interval leakage, nested validation, out-of-fold ownership, supplied resampling decisions and constrained holdout design. Implement deterministic rules and audit their boundary cases.
These problems are original practice. They are not questions from a named employer or a live hiring loop.
1.Allocate contiguous fold remainders explicitly
Write
contiguous_folds(n,k), integers n>=0,k>=1. Split indices 0..n-1 into k consecutive test blocks; the first n%k blocks have n//k+1 rows, others n//k. Return[train_indices,test_indices]for each block in order, both increasing. Training is the full complement. Keep empty blocks when k>n. No mutation.2.Carry a class allocation cursor across labels
Write
class_folds(labels,k,start). labels are strings, k>=1 and 0<=start<k. Visit classes in lexical order, visiting each class's row indices increasingly. Assign visited rows cyclically to folds starting at start; DO NOT reset the cursor between classes. Return k test-index lists, each sorted. Empty folds remain. No mutation.3.Place largest indivisible groups before smaller ones
Write
group_folds(groups,k). groups lists a string group ID per row; k>=1. Visit distinct groups by decreasing row count, ties by group ID. Assign each whole group to the fold with smallest current row load, ties by fold index. Return k sorted test-index lists. Include empty folds. No mutation.4.Choose a whole-group holdout by ordered balance objectives
Write
balanced_holdout(groups,target_size,targets). groups maps <=12 string IDs to lists of string class labels. targets maps every observed class to a nonnegative target count;target_size>=0 integer. Choose any subset of groups minimizing (absolute row-count error, sum of absolute class-count errors, sorted chosen IDs), in that priority. Return[chosen_IDs,size_error,class_error]. No mutation.5.Route multilabel rows using their globally rarest label
Write
rare_label_folds(rows,k), k>=1; rows lists string-label lists. Deduplicate row labels. Global frequency counts rows containing each label. Process rows in input order. For a nonempty row choose its rarest label, lexical ties, then the fold with fewest occurrences of that label, ties by fold size then index. Empty-label rows use size then index. Update ALL row labels. Return k index lists.6.Find the lexical feasible fold coloring
Write
conflict_folds(ids,conflicts,k). ids are <=10 unique strings; conflicts are known ID pairs that must occupy DIFFERENT folds, k in 1..3. Sort IDs and return[sorted_IDs,lexicographically_smallest_feasible_fold_vector]with fold numbers 0..k-1, orNoneif impossible. A self conflict is impossible; repeated/reversed conflicts add no condition. Not every fold must be used. No mutation.7.Enumerate every p-group validation complement
Write
leave_groups(groups,p). groups gives a string ID per row, at most 8 distinct; p>=0 integer. For every p-element combination of sorted distinct groups, return[held_group_IDs,train_indices,test_indices]in combination order; row indices increase. Hold out whole groups. p=0 emits one all-training design; p>number_of_groupsemits none. No mutation.8.Quarantine a group with opposing protected roles
Write
protected_split(groups,train_rows,validation_rows). groups gives a string per row; requested row indices are valid, may repeat. A group touched by BOTH requests is quarantined in full; validation-only groups go to validation; every other group goes to training. Return[train_indices,validation_indices,quarantined_indices], each increasing. Never split a conflicted group. No mutation.9.Use label readiness when constructing forward training sets
Write
mature_splits(rows,queries). rows are integer[feature_time,label_ready_time], ready>=feature; queries are[cutoff,positive_horizon]. Per query return increasing[train_indices,validation_indices]. Train requiresfeature_time<cutoff ANDready_time<=cutoff. Validation requires cutoff<=feature_time<cutoff+horizon, regardless of label readiness. Late earlier rows are in neither. No mutation.10.Keep a gap and bounded history in rolling validation
Write
rolling_splits(n,min_train,width,step,gap,max_train). Integers n>=0,min_train,width,step>0, gap>=0,max_train>=min_train. Test starts atmin_train+gap then advances by step; emit only full width-sized tests inside 0..n-1. Training ends just before the gap and keeps at mostmax_trainpreceding rows. Return[train_indices,test_indices]per window. No mutation.11.Purge closed label intervals touching a test interval
Write
purge_intervals(intervals,test_rows). Integer closed intervals[start,end], start<=end;test_rowsvalid indices, repeats allowed. Among non-test rows, purge every interval intersecting ANY test interval, including endpoint equality and spanning intervals. Return[retained_train_indices,purged_indices], increasing. Empty test set retains all rows. No mutation.12.Apply embargo only after merged validation blocks
Write
embargo_split(times,blocks,gap). Integer times; closed blocks[a,b], a<=b; gap>=0 integer. Merge overlapping/touching blocks. Test rows lie in merged blocks. Other rows in (block_end,block_end+gap] are embargoed; remaining rows train. Return[train_indices,test_indices,embargoed_indices], increasing. Test membership takes priority over embargo. No mutation.13.Hold out timestamp buckets rather than individual tied rows
Write
latest_entity_split(rows,p). rows are[string_entity,integer_time], p>=0. For each entity independently, hold out its p latest DISTINCT timestamps, or all timestamps if fewer exist. All rows tied at a chosen timestamp go to validation. Return[train_indices,validation_indices], increasing. p=0 holds out nothing. No mutation.14.Quarantine whole sessions that straddle a cutoff
Write
session_split(rows,cutoff,gap). rows are[string_entity,integer_time], gap>=0. Per entity sort by (time,index). Consecutive rows belong to one session while time difference<=gap, transitively. A session entirely before cutoff trains; entirely at/after cutoff validates; a straddling session is quarantined. Return three increasing index lists[train,validation,quarantine]. No mutation.15.Reject ambiguous out-of-fold prediction ownership
Write
assemble_oof(n, batches). n>=0; each batch is[row_indices,predictions]of equal lengths, indices valid in 0..n-1, predictions finite. Return[values,missing_indices,ambiguous_indices].values[i]is its prediction ONLY if i occurs exactly once across all batches; otherwiseNone. No occurrence is missing; two or more are ambiguous even if predictions agree. Index lists increase. No mutation.16.Lift inner positions through outer training indices
Write
lift_inner(outer_train,inner).outer_trainis a list of unique nonnegative ORIGINAL row indices in arbitrary order. Each inner entry is[local_train_positions,local_validation_positions], all valid positions intoouter_train. Return the corresponding pairs of ORIGINAL index lists, preserving entry and position order. Never sort or treat a local position as an original index. No mutation.17.Select by inner losses before revealing an outer score
Write
sealed_selection(inner_losses,outer_losses). Same string config keys in both maps; inner lists have one common positive length, entries finite orNone. Eligible configs have NO missing inner fold. Select smallest inner mean loss, ties by config ID, then return[ID,inner_mean,outer_loss]. Outer loss must not influence selection. No eligible config returnsNone. No mutation.18.Report labels missing from each training complement
Write
training_gaps(labels,test_folds). labels are strings per row; each test fold lists valid row indices, repeats allowed. For each fold return sorted classes present anywhere in labels but ABSENT from its training complement. Test rows are excluded as a set. A class missing only from validation is not a training gap. Preserve fold order. No mutation.19.Replay full-group bootstrap draws and out-of-bag support
Write
group_bootstrap(groups,draws). groups is a string group ID per row; draws are known group IDs, possibly repeated. Return[in_bag_row_indices,out_of_bag_row_indices]. For each draw append ALL matching source indices in source order; repeated draws repeat the whole group. Out-of-bag rows are groups never drawn, increasing. Empty draws leave every row out of bag. No mutation.20.Rank supplied weighted sampling clocks
Write
clock_sample(rows,m). rows have unique string ID, finite weight>=0 and supplied 0<u<1 as[ID,weight,u]; m>=0 integer. Ignore zero weights. Score=-ln(u)/weight; return IDs of at most m smallest scores in score order, ties by ID. Do not draw randomness, repeat IDs or include zero-weight rows when too few positive rows exist. No mutation.21.Replay reservoir replacement decisions without sorting slots
Write
reservoir_replay(ids,capacity,draws). ids unique strings; capacity>=0 integer. Initially store the firstmin(capacity,n)IDs. For each later source index i, consume its supplied integer draw j in 0..i; if j<capacity replace reservoir slot j, otherwise keep it unchanged. Return[reservoir_in_slot_order,unselected_IDs_in_source_order]. draws has exactly one entry per later row. No mutation.22.Keep fractional spacing until the final index floor
Write
systematic_indices(n,m,offset). Integers 0<=m<=n. If m=0 return []; otherwise 0<=offset<n/m is supplied. Returnfloor(offset+j*n/m)for j=0..m-1, in that order. Interpret decimal inputs exactly and floor only the final position; do not truncate n/m to an integer step. No randomness or mutation.23.Assign remaining quota slots by exact fractional remainder
Write
proportional_quota(sizes,total). sizes maps string strata to nonnegative integer population sizes; 0<=total<=sum(sizes). If population is zero return all keys with quota zero. Otherwise floor total*size/population per stratum, then give remaining slots to largest fractional remainders, ties by stratum name. Return a quota map retaining zero strata. Use exact arithmetic. No mutation.24.Choose validation groups under a strict collection budget
Write
budget_groups(groups,budget). groups maps <=16 unique string IDs to[positive_integer_cost,nonnegative_integer_utility], budget>=0 integer. Select any whole-group subset with total cost<=budget. Maximize total utility, then minimize cost, then choose lexical smallest sorted ID list. Return[IDs,cost,utility]. Empty selection is allowed. No mutation.25.Exclude neighboring tiles around spatial validation regions
Write
spatial_split(points,width,validation_tiles,radius). Integer[x,y]points; width>0,radius>=0 integers. Tile=(x//width,y//width), including negative coordinates. Supplied validation tiles hold out all their rows. Other rows within Chebyshev tile distance<=radius of ANY supplied validation tile are buffered out; all others train. Return increasing[train,test,buffer]index lists. No mutation.26.Keep user-cold and item-cold assessment quadrants distinct
Write
cold_quadrants(edges,held_users,held_items). edges are[string_user,string_item]observations, repeats allowed. Return four increasing index lists: neither endpoint held (train), held user only, held item only, both endpoints held. Held ID lists may repeat or include unseen identities. A repeated edge is a separate observation. No mutation.27.Hold out edges while preserving endpoint training support
Write
degree_holdout(edges,min_degree). <=12[user,item]string edges;min_degree>=0 integer. Choose held row indices so EVERY originally seen user and item retains at leastmin_degreetraining edges, counting repeats. Maximize held row count, ties by lexical increasing index list. Return held indices, orNoneif even the full training graph violates a floor. No mutation.28.Minimize fold reassignment cost under capacities and locks
Write
repair_folds(costs,capacities,locks). n<=8 rows, k=1..3 folds; costs is n-by-k nonnegative integer move costs. capacities are nonnegative integers summing to n. locks maps valid row indices AS STRINGS to required fold indices. Choose assignments meeting exact capacities and all locks; minimize total cost, ties by lexical fold vector. Return[vector,cost], orNoneif infeasible. No mutation.29.Group repeated training designs by their actual complements
Write
repeated_designs(n,test_folds). n>=0; each fold contains valid test indices, repeats allowed. Canonical training design is the sorted complement of the SET of test indices. Group identical training designs. Return[first_fold_index,all_member_fold_indices,train_indices]per group in first-fold order. Test ordering and repeated references do not create a new design. No mutation.30.Prune partial validation only with a strict optimistic bound
Write
prune_bounds(losses,low,high). losses maps string IDs to common nonempty lists, entriesNoneor finite loss in[low,high], low<=high. Best completed config minimizes (mean,ID). For each ID return[ID,optimistic_mean,pruned], sorted by ID; replace missing losses with low for its bound. Prune iff a completed best exists and (bound,ID)>(best_mean,best_ID). Return[best_ID_or_None,rows].