CODING CHALLENGE · N°62

Config Validator

Easy FDEReliabilityIntegrations

Half of "it doesn’t work at the customer" is a bad config — a missing key, a string where an int belongs, an env that isn’t allowed. Validate it up front and fail loudly with a clear list, instead of crashing three layers deep. Solve it in Python or TypeScript, with hidden tests.

The problem

Implement validate_config(config, spec). spec maps each key to a rule: {"type": "int"|"str"|"bool", "required": bool (optional), "allowed": [...] (optional)}. Return a sorted list of error strings: "missing: KEY" for a required key that’s absent, "wrong type: KEY" for a present key of the wrong type, and "not allowed: KEY" for a correctly-typed value outside its allowed list. A correct config returns [].

EXAMPLE 1
Input config = {"port":8080,"env":"x","debug":"yes"}, spec = {"port":{"type":"int","required":true},"env":{"type":"str","allowed":["dev","prod"]},"debug":{"type":"bool"},"host":{"type":"str","required":true}}
Output ["missing: host", "not allowed: env", "wrong type: debug"]
host absent, env not in allowed, debug is a string not a bool
CONSTRAINTS
  • A missing key is only an error if it is required; an absent optional key is fine and gets no further checks.
  • Type check first; only if the type is correct do you check allowed.
  • Booleans are not integers — True must fail an "int" check (and vice-versa).
  • Return the errors sorted.
SOLVE IT YOURSELF

Your turn — write it

Edit the stub, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? the hints are right above and Reveal solution is one click away.

YOUR TASK

Implement validate_config(config, spec): for each spec key, handle absence (error only if required), then type, then allowed-values. Collect messages and return them sorted.

HINTS — 4 IDEAS
  1. If the key isn’t in the config: push "missing: KEY" only when the rule is required, then skip it.
  2. Type-check with the exact type — and remember a bool is not an int in this exercise.
  3. If the type is wrong, record "wrong type: KEY" and don’t also check allowed.
  4. If typed correctly but there’s an allowed list the value isn’t in, record "not allowed: KEY".
CPython · WebAssembly

Explore the topic

See this challenge alongside everything else on the same subject — handbooks, system designs, algorithms and tools, in one place.