Copy List With Random Pointer
Create a deep copy of a linked list with next and random pointers. Each random pointer targets any node in the list or null. Preserve values and all edges, using entirely new nodes. Input is an array of [value, randomIndexOrNull] pairs.
Example 1
head = [[4,2],[9,0],[7,null]][[4,2],[9,0],[7,null]]Explanation
Copy the chain and random edges 0->2, 1->0, 2->null into fresh nodes.
Example 2
head = [[2,0]][[2,0]]Explanation
The copied node's random pointer must refer to itself, not the original.
Example 3
head = []nullExplanation
A null head copies to null without allocation.
Constraints
- 0 <= number of nodes <= 1000
- random indices are zero-based and valid
- next follows array order
Function contract
copyRandomListArguments: randomListSolutionRuns on your device
Loading draft…
Run: 3 examples; Submit: 34 cases, on your device.
[[4,2],[9,0],[7,null]]