Schema and Record Validation
Original Python data engineer interviews on precise ingestion contracts, schema evolution, nested records, typed keys, reference support, rule dependencies and atomic quarantine.
These problems are original practice. They are not questions from a named employer or a live hiring loop.
1.Parse an exact fixed-scale ingestion field
Write
minor_units(text, scale), scale integer 0..9. Accept only an optional leading +/-, at least one ASCII digit, and optionally a dot plus 1..scale ASCII digits. A dot is forbidden at scale 0. Return the signed integer after right-padding fractional digits to scale, orNonefor any invalid text. No whitespace, exponent or Unicode digits; negative zero returns 0.2.Bind schema columns through an untrusted header
Write
bind_header(header, required, rows). Names are strings; required unique. Return {"columns":[[name,only_index_or_None]],"duplicates":[[name,indices]],"missing":names,"bad_width":row_indices}. columns and missing follow required order; duplicates lists all repeated header names, sorted. Duplicate required names have indexNone.bad_widthcompares each row to header length. No mutation.3.Migrate field names without sequential overwrite
Write
migrate_fields(record, renames). String-key maps. Each present source targetsrenames.get(source,source); absent sources in renames do nothing. Return{"record": migrated_or_None,"collisions":[[target,sorted_sources]]}. Sort collisions by target; any collision rejects the whole migration, even when values agree. Swaps are simultaneous. No mutation.4.Materialize defaults without replacing explicit nulls
Write
materialize(record, schema). schema maps name to[required,nullable,default_value]. For an absent field, required means error"missing"; otherwise insert its default unchanged, evenNone. For a presentNone, error"null"iff not nullable. Ignore extras. Return{"record":schema-only_result_or_None,"errors":[[name,reason]]}, errors sorted by name. No mutation.5.Check a reader against declared conversion paths
Write
reader_gaps(writer, reader, edges). writer maps field to type-name string; reader maps field to[type_name,optional]. edges lists directed[source_type,target_type]conversions, with cycles allowed. A present field is readable if its writer type reaches its reader type, including zero steps. Only absent optional fields are exempt. Return sorted[field,"missing"/"type"]gaps. No mutation.6.Audit field evolution by stable identifier
Write
field_evolution(old, new). Each list has[stable_id,name,type]strings, unique IDs and names within a list. Return {"added":ids,"dropped":ids,"renamed":[[id,old_name,new_name]],"retyped":[[id,old_type,new_type]]}; all lists sorted by ID. Matching uses ID only. A rename and retype can both apply to one ID. Reusing a name with a different ID means drop plus add. No mutation.7.Validate a record through its declared variant
Write
tagged_errors(record, variants). record must have string"kind"naming a variants key; otherwise return [["kind","tag"]]. Each variant is[required_names,allowed_names,nullable_names], all exclude kind; required is a subset of allowed. For a known tag report absent required as"missing", present nonnullableNoneas"null", and nonallowed fields as"extra". Sort by field. No mutation.8.Resolve nested paths with structural diagnostics
Write
resolve_path(value, path). path tokens are strings or nonnegative ints, excluding bool. A string requires a dict and names a member; an int requires a list and indexes it. Return{"value":result,"error":None}on success, else{"value":None,"error":[token_index,reason]}, reason"container","missing"or"index". Empty path returns value, includingNone. First failure wins. No mutation.9.Require exactly one strict record shape
Write
union_match(record, branches). branches maps name to a field schema of"int","str"or"bool". Match iff keys are exact and values have strict types; bool is not int,Nonenever matches. Return {"selected":sole_name_or_None,"matches":sorted_names,"errors":[[branch,sorted_bad_fields]]}. errors: failed branches sorted by name; absent/extra keys are bad. No mutation.10.Parse the supplied single-record quoting grammar
Write
split_record(text). Fields are separated by |. An unquoted field contains no quote, |, CR or LF. A quoted field starts with", doubles an internal quote as "", and ends with "followed only by | or end. Quoted fields may contain |, CR and LF. Return decoded string fields, orNonefor invalid framing. Empty text is one empty field; a final | adds an empty field. No whitespace trimming.11.Check coefficient rescaling and precision exactly
Write
decimal_fit(coefficient, source_scale, precision, target_scale). Integers; scales >=0 and precision>=1. Value is coefficient*10**(-source_scale). Return its integer coefficient attarget_scaleiff rescaling is exact andabs(result)<10**precision, elseNone. Dropping only zero fractional digits is exact; do not round. Precision limits coefficient digits, including zeros implied by scale.12.Find every duplicate group under typed key equality
Write
typed_duplicates(rows, fields). rows are dicts; fields unique strings. Key components areNone, bool, int or str. Ignore rows missing any key field. Match complete keys by strict type/value per component;Noneis a key value. Return index lists for groups of size>=2, sorted by first index, members in input order. Empty fields puts all rows in one group. No mutation.13.Separate exempt and unsupported composite references
Write
reference_rows(parents, children). Both list equal-width keys, width>=1; components str/None, parents nonnull. Child all-null keys are exempt; partially null keys fail as partial; complete keys absent from parents fail as unknown. Return{"valid":indices,"exempt":indices,"partial":indices,"unknown":indices}, each in child order. Parent repeats add no support. No mutation.14.Audit both cardinality bounds and orphan children
Write
cardinality(parents, children, low, high). parents unique string IDs, children string parent references; integers 0<=low<=high. Return{"violations":[[parent,count]],"orphans":child_indices}. Count every repeated child; include parents with zero children. violations follows parents order and includes counts outside inclusive bounds. orphans follows child order. No mutation.15.Enforce exactly one supplied field per family
Write
exclusive_fields(record, families). families lists nonempty lists of distinct field names; a field may occur in several families. Presence means key membership, includingNone,Falseand empty string. Return [[family_index,present_names]] for every family whose present count is not exactly one. Preserve family order and the names within each family. No mutation.16.Apply exact-type discriminator requirements
Write
conditional_missing(record, rules). Each rule is[discriminator,expected,required_names]; discriminator values areNone/bool/int/str. Trigger only for a present discriminator with strict type/value equality. A required member must exist and be nonnull;False, 0 and "" satisfy it. Return [[rule_index,missing_names]] for triggered failing rules, preserving rule/name order. No mutation.17.Check explicit lower and upper record boundaries
Write
boundary_errors(rows, lower, upper). Each field is absent,Noneor a finite int/float excluding bool; lower and upper distinct strings. Return [[row_index,reason]], at most one per row:"missing"if either key absent, else"null"if either value isNone, else"reversed"if lower>upper. Equal endpoints are valid. Compare numeric values as exact decimal spellings. No mutation.18.Infer a nested list shape or reject ragged records
Write
record_shape(value). JSON scalars and dicts are atomic with shape []; a list has shape[length]+child_shapeonly if every child has the same recursively valid shape. Empty list shape is[0]. Return the dimension list, orNonefor any ragged/mixed-depth structure. Dict contents are not traversed. No mutation.19.Find only minimal complete unique field combinations
Write
candidate_keys(rows, fields). fields unique strings, at most 8; rows dicts whose present values are strings orNone. A nonempty field subset is a key iff every row contains nonnull values for it and composite tuples are unique. Return only inclusion-minimal keys as field-name lists in fields order, sorted by size then field-index tuple. Empty rows returns []; no empty key. No mutation.20.Audit reference support with multiplicity
Write
bag_deficits(available, required). Lists of string tokens; every available occurrence supports at most one matching required occurrence. Return{"matched":indices,"unmatched":indices,"unused":[[token,count]]}. Match required rows in input order; unused lists positive remaining counts sorted by token. Duplicate evidence must not be collapsed to set membership. No mutation.21.Propagate failed rule prerequisites without rerunning them
Write
rule_states(dependencies, outcomes). dependencies maps rule name to prerequisite names; all names are keys and the graph is acyclic. outcomes maps every rule toTrue,FalseorNone. A rule is"blocked"if any prerequisite state is not"pass"; otherwiseTruegives"pass",False"fail",None"skip". Blocked overrides its own outcome. Return [[name,state]] sorted by name. No mutation.22.Quarantine every member of repeated record keys
Write
collision_quarantine(rows, key). rows dicts; key values if present are strings orNone. Missing/null keys are"invalid". Every row with a nonnull key occurring more than once is"collision", including its first row. Other rows are"valid". Return{"valid":indices,"invalid":indices,"collision":indices}, all in input order. Empty string is a valid key. No mutation.23.Encode typed records as deterministic structural identity
Write
typed_tree(value). Input is a JSON tree with string dict keys and scalarsNone/bool/int/str (no floats). Encode scalars as["null"],["bool",value],["int",value],["str",value]; lists as["list",encoded_items]; dicts as ["dict",[[key,encoded_value],...]] sorted by key. Return the tree, preserving list order. No hashing, string concatenation or mutation.24.Separate absent null and concrete observed field types
Write
schema_evidence(rows). rows are string-key dicts; valuesNone/bool/int/str/list/dict. Return [[field,absent_count,null_count,sorted_type_names]], fields sorted. Include every field appearing anywhere; type names are"bool","int","str","list","dict"and exclude null. Count absence per row, not from nulls. Empty batch returns []. No recursive inference or mutation.25.Validate numeric bounds and grid alignment exactly
Write
grid_errors(values, lower, upper, origin, step). Finite int/float values excluding bool; lower<=upper, step>0. Interpret every decimal spelling exactly. Return [[index,reason]],"bounds"if value is outside inclusive[lower,upper], else"grid"if (value-origin)/step is not an integer. Bounds takes precedence; origin may lie outside bounds. No rounding or mutation.26.Audit many-to-one normalization of source headers
Write
header_collisions(names). Normalize each string by stripping only ASCII space and tab at both ends, then replacing only ASCII A..Z with a..z; preserve all other characters. Return [[normalized,[[index,original],...]],...] for normalized names appearing at least twice, sorted by normalized string. Repeated identical spellings still collide. No mutation.27.Propagate any invalid record to its whole ingest group
Write
atomic_groups(groups, invalid). groups gives a string transaction ID per row; invalid lists distinct valid row indices. Reject every row of a group containing any invalid row. Return{"accepted":indices,"rejected":indices,"causes":[[group,invalid_indices]]}. Row lists follow input order; causes follows each rejected group's first appearance in groups, with cause indices sorted. No mutation.28.Apply guarded record patches atomically
Write
guarded_patch(record, guards, sets, removes, required). ValuesNone/bool/int/str. guards: field->[present,old_value]; false requires absence, true strict type/value equality on original record. Apply disjoint sets/removes together; required fields must then exist nonnull. Return{"record":result_or_None,"guards":sorted_failed,"required":sorted_failed}. Report both error lists. No mutation.29.Compare nested record leaves with declared paths
Write
leaf_coverage(record, required). record is a nested string-key dict; nondicts and empty dicts are leaves. required lists unique nonempty string-token leaf paths. Return{"missing":path_indices,"blocked":path_indices,"extra":leaf_paths}. blocked: proper prefix is a leaf; missing: absent member or nonempty dict terminal. extra: undeclared leaves, lexicographically sorted. No mutation.30.Choose exact minimum-cost removals for record conflicts
Write
conflict_removals(costs, conflicts). costs gives positive integer removal costs for <=12 rows. conflicts lists[i,j]with distinct valid indices; a pair forbids keeping both rows. Return ascending removed indices minimizing (total_cost,number_removed,index_list) lexicographically. Every conflict needs at least one endpoint removed; duplicate/reversed pairs add no constraint. No mutation.