KatInterview

Serialize and Restore Object Graphs Containing Cycles

System DesignModel answer
HardModel answerSystem Designserializationgraphscycle-detection

Last updated

Design a cross-language JSON format and matching encoder/decoder that correctly handles circular references, shared subobjects, and hostile inputs.

Serialize and Restore Object Graphs Containing Cycles

Background

Standard JSON serializers crash or loop infinitely when they encounter a cycle. Consider two nodes that each hold a reference to the other:

a = {"name": "Alice"}
b = {"name": "Bob", "partner": a}
a["partner"] = b

A naive recursive encoder follows a → b → a → b → … until the stack overflows. You need a design that handles this gracefully.

Your task

Design a complete serialization and deserialization strategy for object graphs that may contain cycles or shared subobjects. The inputs are rooted object graphs whose values are strings, integers, or dictionaries with string keys. No other types need to be supported.

Your answer should cover:

  1. Wire format — What does the JSON output look like? Define the schema precisely enough that any language could implement a compatible decoder.
  2. Encoding algorithm — How do you detect cycles, assign stable IDs that do not depend on memory addresses, prevent infinite recursion, and preserve shared subobjects (i.e., two references to the same dict must decode back to the same object, not two equal copies)?
  3. Traversal order — Should you use BFS or DFS? Does the choice matter for correctness? Does it matter for determinism or human readability?
  4. Decoding algorithm — How do you reconstruct cycles and shared references from the flat format?
  5. Determinism — What must be true for the same graph to always produce the same bytes, across runs and across machines?
  6. Security and validation — What checks does the decoder need to safely handle malicious or malformed input?
  7. Complexity — What is the time and space complexity of encoding and decoding?
  8. Trade-offs — Briefly compare your chosen design with at least one alternative (e.g., inline anchor/alias schemes, type-tagged formats, or lazy reference resolution).

Expected output

A structured prose design plus a reference implementation in Python. Your implementation should pass a round-trip test: after encoding and decoding the a/b example above, result["partner"]["partner"] is result must be True.

Constraints

  • Output must be valid JSON parseable by any standards-compliant parser.
  • IDs in the output must not be memory addresses or any other process-local value.
  • The encoder must not use recursion in a way that fails on a 1 000 000-node linked list.
  • The decoder must reject oversized, structurally invalid, or otherwise hostile payloads.

Hints

Hint 1

Cycle detection and shared-object tracking are the same problem: if you record every dict you have already seen, a second encounter means either a cycle or a shared reference — handle both the same way by emitting a reference rather than expanding the object again.

Hint 2

Flatten the graph into an array: each dict gets one slot, its index is its stable ID, and every reference inside an entry becomes {"$ref": n}. This caps JSON nesting depth at a small constant regardless of graph depth, so neither your code nor the JSON parser can stack-overflow.

Hint 3

Decode in two explicit passes: first allocate one empty dict per slot, then fill in the values. Because every target object already exists before any field is resolved, forward references and back-edges (cycles) need no special handling — they are just array lookups.