Skip to main content

Copy a List With Random Pointers

MediumLinked listHash map153 tests

You are given head, the first node of a linked list. Every node has three fields:

  • val — an integer,
  • next — the next node, or null at the end,
  • random — any node of this same list (it can be the node itself), or null.

Return a deep copy of the list: a new list built from new nodes, one new node for each original node. In the copy, each node has the same val as its original, and its next and random point to the copies of the nodes the original pointed to. No pointer in the copy may point to an original node.

How the input is shown

Each node is shown as [val, randomIndex], from head to tail. randomIndex is the position (counting from 0) of the node that random points to, or null. For example, [[4, null], [9, 0]] is the list 4 -> 9, where the random pointer of 9 points to 4. An empty list is []. Your returned copy is shown in the same way.

Note

  • Two nodes can have the same value, so you cannot find a node by its value.
  • If the list is empty, return null.
  • Hint: walk the list once and make a copy of every node, storing original -> copy in a map. Walk it a second time and set each copy's next and random by looking up the map.

Examples

Example 1

Input:
[[4,null],[9,0],[2,2]]
Output:
[[4,null],[9,0],[2,2]]

The copy has new nodes 4 -> 9 -> 2. The random pointer of the new 9 points to the new 4, and the random pointer of the new 2 points to itself.

Example 2

Input:
[[6,2],[6,2],[1,null]]
Output:
[[6,2],[6,2],[1,null]]

Both nodes with value 6 have their random pointer on the node with value 1. In the copy, both must point to the new 1.

Example 3

Input:
[]
Output:
[]

The list is empty, so the copy is empty too: return null.

Constraints

  • 0 <= number of nodes <= 40
  • -100 <= Node.val <= 100
  • Node.random is null or a node of the same list.

Run checks your code against the 3 examples. Submit checks it against all 153 tests and needs a free account. You can also try ideas in the free JavaScript or Python compiler.