Flat Error Collection from a Recursive Schema Validator
Trees & GraphsAuto-graded · 13 test casesLast updated
Tests ability to traverse a nested schema definition, flatten heterogeneous check results, and enforce a consistent empty-list contract across all node types.
Flat Error Collection from a Recursive Schema Validator
A schema-validation system checks records against a tree-shaped schema and produces a flat list of human-readable error strings for each record. Your job is to implement the engine that walks the schema tree, runs every check, and collects the results in document order.
Schema node types
A schema is a plain dictionary. Three node types exist, identified by the "type" key.
"field" — validates a single scalar value.
| Key | Type | Meaning |
|---|---|---|
"name" | str | field name, used as the prefix in error messages |
"required" | bool (optional, default False) | if True and the value is None, add "<name>: required" |
"checks" | list (optional, default []) | ordered list of check descriptors to run when a value is present |
If the value is None and the field is not required, contribute nothing (empty list).
"group" — validates a nested dict.
| Key | Type | Meaning |
|---|---|---|
"name" | str | group name |
"required" | bool (optional, default False) | same rule as for "field" |
"children" | list | ordered list of child schema nodes |
If the value is None and the group is not required, contribute nothing. If the value is present but is not a dict, add "<name>: expected object" and stop (do not recurse into children). Otherwise recurse into every child, collecting errors in order.
"each" — validates a list of items, each against the same sub-schema.
| Key | Type | Meaning |
|---|---|---|
"name" | str | node name |
"item" | dict | schema node applied to each element |
If the value is None, contribute nothing. Otherwise run the item schema against every element in order and collect all errors.
Check descriptors
Each check descriptor is a dict with a "type" key. A check runs only when the field value is present (not None). The checks and the error strings they produce are:
"type" | Extra key | Error produced (or nothing if the rule passes) |
|---|---|---|
"min_len" | "n": int | "<name>: shorter than <n>" |
"max_len" | "n": int | "<name>: longer than <n>" |
"digits_only" | — | "<name>: digits only" |
"no_spaces" | — | one entry "<name>: space at <i>" per space character, in index order |
A passing check contributes nothing. A check may contribute zero, one, or many error strings; all of them must appear in the output in the order they were produced.
Function signature
def validate_records(schema: dict, records: list[dict]) -> list[list[str]]:
Given a schema node and a list of records, return one flat list[str] per record containing every error message in document order (depth-first, children in the order they appear in the schema). If a record has no errors, return [] for that record, never None.
Constraints
1 ≤ len(records) ≤ 1 000- Schema depth will not exceed 10 levels.
- Field values, when present, are strings.
- Record values for
"group"nodes, when present, are either adictor a non-dict (to trigger the "expected object" error). - Record values for
"each"nodes, when present, are lists. ninmin_len/max_lenchecks is a non-negative integer.- An empty string is a valid present value and must be checked normally.
- Every node type must return
[](notNone) when it has nothing to report.
Examples
Example 1
Input: validate_records({'type': 'group', 'name': 'signup', 'children': [{'type': 'field', 'name': 'username', 'required': True, 'checks': [{'type': 'min_len', 'n': 3}, {'type': 'no_spaces'}]}, {'type': 'group', 'name': 'address', 'children': [{'type': 'field', 'name': 'zip', 'checks': [{'type': 'digits_only'}]}, {'type': 'field', 'name': 'city', 'checks': [{'type': 'min_len', 'n': 2}]}]}, {'type': 'each', 'name': 'tags', 'item': {'type': 'field', 'name': 'tag', 'checks': [{'type': 'max_len', 'n': 8}]}}]}, [{'username': 'jo e', 'address': {'zip': '9a1', 'city': 'Rome'}, 'tags': ['ok', 'verylongtag']}, {'username': 'maria', 'tags': []}, {'username': 'maria', 'address': {'zip': '', 'city': ''}}, {'address': 'Main St'}])
Output: [['username: space at 2', 'zip: digits only', 'tag: longer than 8'], [], ['zip: digits only', 'city: shorter than 2'], ['username: required', 'address: expected object']]
Hints
Hint 1
Start with the 'field' node: iterate its checks, and think carefully about what to do with the result of each one — a check can return None, a single string, or a list of strings. You need all three cases handled without leaking None into your output list.
Hint 2
For 'group' and 'each' nodes, the key question is how to combine child results into the parent's running list. append vs extend makes all the difference between a nested structure and a flat one.
Hint 3
Pick one canonical return value for 'nothing to report' and use it everywhere — field, group, and each — so callers never need to branch on None vs [].
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The schema is a tree. Validating a record means doing a depth-first walk of that tree, running checks at the leaves, and accumulating error strings in document order. Three design decisions determine correctness.
1. Normalize check output before touching the accumulator
A check can return None (passed), a str (one error), or a list[str] (zero or more errors). A flatten helper converts all three to a plain list[str]:
None→[]"some message"→["some message"]["a", "b"](or arbitrarily nested) →["a", "b"]
Crucially, only None is dropped. An empty string is a valid string and passes through unchanged, which matters for field values like "" that are present but fail format checks.
2. Use extend, not append, when collecting child results
Each node type ("field", "group", "each") returns a list[str]. When a parent collects children, it calls errors.extend(child_result) rather than errors.append(child_result). Because every child already returns a flat list, extend keeps the parent flat too — by induction the entire output is flat regardless of schema depth.
3. One canonical "nothing to report" value: []
Every code path that has no errors returns [], never None. This means the return type is always list[str], callers can iterate or measure it without branching, and the output for an error-free record is [].
Why it is correct
- No
Nonein output:flattendropsNonefrom check results; all optional-missing paths return[]. - Flat output:
extendat every collection site;flattenhandles any nesting a check might return. - Consistent empty value: all three node types return
[]for "nothing to report". - Empty string is a value:
flattendrops onlyNone, so""is never confused with a missing value. - Document order: children are processed in the order they appear in the schema;
no_spacesproduces space errors in index order.
Complexity
Let N = number of records, S = number of schema nodes, V = total length of all string values across all records. Each schema node is visited once per record, and each character is examined at most once by no_spaces or isdigit. Overall time is O(N × S + V); space is O(S + E) where E is the total number of error strings produced.
Reference solution
from typing import Any
def validate_records(schema: dict, records: list[dict]) -> list[list[str]]:
def flatten(value: Any) -> list[str]:
"""Normalize a check result to a flat list of strings.
None means the check passed — contribute nothing.
A string is a single error message.
A list may contain any mix of the above, to any depth.
An empty string is a valid message and is kept.
"""
if value is None:
return []
if isinstance(value, str):
return [value]
if isinstance(value, list):
result = []
for item in value:
result.extend(flatten(item))
return result
return []
def run_check(check: dict, name: str, value: str) -> list[str]:
"""Run a single check descriptor against a present string value."""
kind = check["type"]
if kind == "min_len":
return flatten(
f"{name}: shorter than {check['n']}" if len(value) < check["n"] else None
)
if kind == "max_len":
return flatten(
f"{name}: longer than {check['n']}" if len(value) > check["n"] else None
)
if kind == "digits_only":
return flatten(None if value.isdigit() else f"{name}: digits only")
if kind == "no_spaces":
return flatten(
[f"{name}: space at {i}" for i, ch in enumerate(value) if ch == " "]
)
raise ValueError(f"Unknown check type: {kind}")
def validate(node: dict, value: Any) -> list[str]:
"""Recursively validate a value against a schema node."""
kind = node["type"]
name = node["name"]
if kind == "field":
if value is None:
return [f"{name}: required"] if node.get("required", False) else []
errors: list[str] = []
for check in node.get("checks", []):
errors.extend(run_check(check, name, value))
return errors
if kind == "group":
if value is None:
return [f"{name}: required"] if node.get("required", False) else []
if not isinstance(value, dict):
return [f"{name}: expected object"]
errors = []
for child in node.get("children", []):
errors.extend(validate(child, value.get(child["name"])))
return errors
if kind == "each":
if value is None:
return []
errors = []
for item_value in value:
errors.extend(validate(node["item"], item_value))
return errors
raise ValueError(f"Unknown node type: {kind}")
return [validate(schema, record) for record in records]