Nested Message Schema: Size and Field Type Queries
Data Structure DesignAuto-graded · 17 test casesLast updated
Parse a mini protobuf-style schema from text, then answer batched size and field-type queries with nested messages, forward references, and cycle and error handling.
You are given the text of a small schema written in a simplified protobuf-like language, plus a batch of queries to run against it. Write a function that parses the text, validates it, and returns one answer per query.
Schema format
The text contains zero or more message definitions:
message Name {
type field_name = number;
...
}
- A message has a name and a (possibly empty) list of fields.
- Each field is
type field_name = number;. The type is either a scalar type or the name of a message defined anywhere in the same text, including later in the text. - Whitespace and line layout do not matter. Tokens may be separated by any amount of whitespace, including newlines, or may sit on one line.
//line comments and/* ... */block comments may appear anywhere and must be ignored.- Names are identifiers: a letter or underscore followed by letters, digits or underscores. Field numbers are non-negative integers. Field numbers have no effect on any answer.
Scalar sizes
| Scalar type | Size in bytes |
|---|---|
bool | 1 |
int32 | 4 |
float | 4 |
int64 | 8 |
double | 8 |
The size of a message is the sum of the sizes of its fields. A field whose type is a message contributes that message's full size. There is no per-field overhead, so a message with no fields has size 0. If a field's type is a scalar name, it is treated as that scalar.
Queries
operations[i] is applied to arguments[i]:
"get_size"with[message_name]gives the size of that message. If the message does not exist, the answer isNone."get_type"with[message_name, field_name]gives the type of that field exactly as written in the schema, as a string (a scalar name or a message name). If the message or the field does not exist, the answer isNone.
Return the answers in order as a list.
Errors
Raise ValueError in each of these cases:
- The schema text is malformed. For example, it has an unexpected token, a missing
=,;,{or}, a missing or non-numeric field number, a missing name, or an unterminated field list. - Two messages share a name, or two fields in one message share a name.
- A field's type is neither a scalar type nor a message defined in the schema. This is checked after the entire text is read, so forward references are allowed.
- A
get_sizequery reaches a message that, directly or through embedded messages, contains itself. - An operation name is not
"get_size"or"get_type", or its argument list has the wrong length. operationsandargumentshave different lengths.
Constraints
0 <= len(schema_text) <= 10^50 <= len(operations) == len(arguments) <= 10^4- Names are case-sensitive.
- Embedding chains may be deep, but a valid acyclic schema will have sizes that fit in a normal Python integer.
- A cyclic embedding only produces an error when a
get_sizequery reaches it.get_typequeries are unaffected by cycles.
Examples
Example 1
Input: schema_queries('message Point { int32 x = 1; int32 y = 2; } message Segment { Point start = 1; Point end = 2; double weight = 3; }', ['get_size', 'get_size', 'get_type', 'get_type'], [['Point'], ['Segment'], ['Segment', 'start'], ['Point', 'y']])
Output: [8, 24, 'Point', 'int32']
Example 2
Input: schema_queries('message Empty { } message Later { bool ok = 9; } message Earlier { Later child = 2; int64 value = 1; }', ['get_size', 'get_size', 'get_type'], [['Empty'], ['Earlier'], ['Earlier', 'child']])
Output: [0, 9, 'Later']
Hints
Hint 1
Split the text into tokens first (identifiers, numbers, and the symbols `{ } = ;`), dropping comments. Then parsing becomes a simple walk over a token list.
Hint 2
Store each message as a dictionary from field name to type string. Run the unknown-type check only after every message has been read, so forward references work.
Hint 3
Compute sizes recursively with memoization, and keep a set of messages currently being computed. If you reach one that is already in that set, the embedding is cyclic and you must raise an error.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution has three stages, kept separate so each is easy to reason about.
-
Tokenize. A single regular expression splits the text into comments, identifiers, numbers, the symbols
{ } = ;, and any other stray character. Comment tokens are discarded. Layout differences such as newlines, indentation and one-line schemas disappear at this step, and stray characters survive as tokens that make the parser fail. -
Parse and validate. Walk the token list with an index.
- Each message must start with
message, then a name, then{. - Each field must be
type name = number ;. A helperexpectraisesValueErrorwith a clear message when a token does not match. - Messages are stored as
{message_name: {field_name: field_type}}, which gives constant-time lookup of both a message and a field. - Duplicate message and field names are rejected while parsing.
- Only after the whole text has been read do we check every field type is either a scalar or a known message. Doing this late is what allows forward references.
- Each message must start with
-
Answer queries.
get_typeis two dictionary lookups, returningNoneif either is missing.get_sizeis a recursive sum over fields with a memo dictionary, so each message is computed once. A set of "currently being computed" messages detects cycles: if we re-enter a message already in that set, the embedding is cyclic and we raiseValueError.
Why it is correct
- Every field type is known to be a scalar or a defined message before any query runs, so the recursion never meets an undefined name.
- In an acyclic schema, a message's size depends only on strictly "smaller" messages in the embedding graph, so the recursion terminates and memoization returns the same value on every visit.
- In a cyclic schema, a depth-first traversal that reaches a message currently on the recursion stack has found a cycle, so the size would be infinite and an error is correct.
- Field numbers and names never enter the sum, which matches the size rules.
Complexity
- Tokenizing and parsing: O(L) time and space for text length L.
- Validation: O(F) for F total fields.
- All
get_sizequeries together: each message is computed at most once, so O(F) in total plus O(1) per query afterwards. - Each
get_typequery: O(1). - Overall: O(L + F + Q) time and O(L + F) space, apart from recursion depth, which equals the longest embedding chain.
Reference solution
import re
from typing import List, Optional
def schema_queries(schema_text: str, operations: List[str], arguments: List[List[str]]) -> List[Optional[object]]:
scalar_sizes = {"bool": 1, "int32": 4, "float": 4, "int64": 8, "double": 8}
ident = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
token_pattern = re.compile(
r"//[^\n]*|/\*[\s\S]*?\*/|[A-Za-z_][A-Za-z0-9_]*|[{}=;]|\d+|[^\s]"
)
tokens = [
t for t in token_pattern.findall(schema_text)
if not t.startswith("//") and not t.startswith("/*")
]
messages = {}
pos = 0
def expect(value):
nonlocal pos
if pos >= len(tokens) or tokens[pos] != value:
got = tokens[pos] if pos < len(tokens) else "end of input"
raise ValueError(f"Expected {value!r}, got {got!r}")
pos += 1
while pos < len(tokens):
expect("message")
if pos >= len(tokens) or not ident.fullmatch(tokens[pos]):
raise ValueError("Expected message name")
name = tokens[pos]
pos += 1
if name in messages:
raise ValueError(f"Duplicate message: {name}")
expect("{")
fields = {}
while pos < len(tokens) and tokens[pos] != "}":
if pos + 4 >= len(tokens):
raise ValueError("Incomplete field declaration")
field_type, field_name = tokens[pos], tokens[pos + 1]
if not ident.fullmatch(field_type) or not ident.fullmatch(field_name):
raise ValueError("Expected field type and name")
pos += 2
expect("=")
if pos >= len(tokens) or not tokens[pos].isdigit():
raise ValueError("Expected numeric field number")
pos += 1
expect(";")
if field_name in fields:
raise ValueError(f"Duplicate field: {field_name}")
fields[field_name] = field_type
expect("}")
messages[name] = fields
for msg_name, fields in messages.items():
for field_type in fields.values():
if field_type not in scalar_sizes and field_type not in messages:
raise ValueError(f"Unknown field type {field_type!r} in message {msg_name!r}")
if len(operations) != len(arguments):
raise ValueError("operations and arguments must have equal length")
cache = {}
active = set()
def size_of(name):
if name not in messages:
return None
if name in cache:
return cache[name]
if name in active:
raise ValueError(f"Embedding cycle involving {name!r}")
active.add(name)
total = 0
for t in messages[name].values():
total += scalar_sizes[t] if t in scalar_sizes else size_of(t)
active.discard(name)
cache[name] = total
return total
results = []
for op, args in zip(operations, arguments):
if op == "get_size" and len(args) == 1:
results.append(size_of(args[0]))
elif op == "get_type" and len(args) == 2:
fields = messages.get(args[0])
results.append(fields.get(args[1]) if fields is not None else None)
else:
raise ValueError(f"Invalid operation or arguments: {op!r}")
return results