Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Print Simple Objects With Cycles

MediumPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Print Simple Objects With Cycles. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Tipalti debugging tools need a deterministic utility that can print a simple object graph. Each object has public properties whose values are JSON primitives or references to other simple objects. Implement a serializer that expands each object once, sorts properties alphabetically, and represents later references, including cycles, as @object_id.

The function should return a string rather than writing directly to standard output so callers can log or test the result.

Formal Specification

Implement print_simple_object(graph, root):

  • graph is a dictionary mapping unique object IDs to property dictionaries.
  • Each property value is a JSON primitive, or a reference of the form {"$ref": object_id}.
  • root is the ID of an object in graph.
  • Return the root object in the format {key: value, ...}.
  • Sort every object's property names lexicographically.
  • Strings use JSON quoting. Booleans and null use JSON-compatible lowercase spellings.
  • Expand an object only on its first visit. Any later visit returns @object_id. This includes both shared references and back-edges in cycles.

Constraints

  • 1 <= number of objects <= 10^5
  • 0 <= total properties <= 2 * 10^5
  • Object IDs and property names are non-empty strings
  • Every reference targets an object in graph
  • Property values are JSON primitives or {"$ref": object_id}
  • The graph may contain cycles and shared references

Function Signature

def print_simple_object(graph, root):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output