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.
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.
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.
1 <= heap.length <= 10^4; each object has up to 20 keys.0 <= root < heap.length, and every reference points inside heap.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).
I'm here to help with #742 Clone a Graph of Objects. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.