Skip to the code
cf.
+50 XP

#742 Clone a Graph of Objects

hard

structuredClone copies objects even when they point at each other. JSON can't show shared or circular references directly, so this problem uses a heap: heap is an array of objects, and inside them a value { "$ref": i } means "a reference to heap[i]". Every other value is a string, number, boolean, or null.

Write cloneGraph(heap, root) that returns a new heap holding a copy of every object reachable from heap[root], and nothing else. Number the copies in the order a depth-first walk first reaches them: the root's copy is 0; when a value is a reference to an object not copied yet, give that object the next number and walk into it right away, before continuing with the remaining keys. Keys are visited in their order. Rewrite every reference to use the new numbers.

Example 1

Input: heap = [{"name":"root","child":{"$ref":1}},{"name":"child","parent":{"$ref":0}}], root = 0
Output: [{"name":"root","child":{"$ref":1}},{"name":"child","parent":{"$ref":0}}]

The two objects point at each other. Each is copied once, and the cycle is kept.

Example 2

Input: heap = [{"id":"a","next":{"$ref":2},"other":{"$ref":1}},{"id":"b"},{"id":"c","back":{"$ref":0},"same":{"$ref":1}},{"id":"unused"}], root = 0
Output: [{"id":"a","next":{"$ref":1},"other":{"$ref":2}},{"id":"c","back":{"$ref":0},"same":{"$ref":2}},{"id":"b"}]

c is reached first through next, and b is reached inside c, so it gets number 2. unused isn't reachable.

Constraints

  • 1 <= heap.length <= 10^4; each object has up to 20 keys.
  • 0 <= root < heap.length, and every reference points inside heap.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).