KatInterview

Recursive Schema Validation

Trees & GraphsAuto-graded · 20 test cases
MediumAuto-gradedTrees & Graphsrecursionvalidationnested-structures

Last updated

Tests recursive validation of nested dictionaries against a schema with type and presence requirements.

You are given a schema specification and a data dictionary. Your task is to determine whether the data conforms to the schema.

Schema Structure

A schema is a dictionary mapping field names to field specifications. Each specification contains:

  • "type": The expected type of the field's value. This can be:
    • "string" for string values
    • "int" for integer values
    • A nested dictionary (representing a sub-schema for nested objects)
  • "required": A boolean indicating whether the field must be present in the data

Validation Rules

  1. Required fields: If a field is marked required: True and is absent from the data, validation fails.
  2. Type matching: If a field is present in the data, its value must match the declared type:
    • For "string", the value must be a string
    • For "int", the value must be an integer (not a boolean, even though booleans are technically integers in Python)
    • For a nested dictionary type, the value must be a dictionary that recursively validates against the nested schema
  3. Optional fields: Fields marked required: False may be absent. If they are present, they must still match the declared type.
  4. Extra fields: Fields present in the data but not defined in the schema are allowed and should be ignored.

Write a function that returns True if the data is valid according to the schema, and False otherwise.

Constraints

  • The input data is always a dictionary
  • Schema definitions form a tree structure with no circular references
  • Type checking is limited to "int", "string", and nested dictionaries
  • Integer fields must be actual integers, not booleans or other numeric types
  • A field is considered present if its key exists in the data dictionary, regardless of whether its value is None

Examples

Example 1

Input: validate_data({'id': {'type': 'int', 'required': True}, 'metadata': {'type': {'source': {'type': 'string', 'required': True}}, 'required': False}}, {'id': 1, 'metadata': {'source': 'sensor_a'}})

Output: True

Example 2

Input: validate_data({'id': {'type': 'int', 'required': True}, 'metadata': {'type': {'source': {'type': 'string', 'required': True}}, 'required': False}}, {'id': 1, 'metadata': {}})

Output: False

Hints

Hint 1

Walk through the schema fields rather than the data fields to naturally handle extra data keys

Hint 2

For nested schemas, first verify the value is a dictionary before attempting recursive validation

Hint 3

Remember that in Python, bool is a subclass of int, so use exact type checking for integer fields