CodingNodes / Linked List / Copy List With Random Pointer System design Space play · ←→ step · R restart

Problem

Every node of a linked list has a val, a next pointer, and an extra random pointer that can aim at any node of the list, or at nothing.

Build a deep copy of the list: brand new nodes, with the same values, where every next and random pointer of the new list points to new nodes, never to the original ones. Return the head of the copy.

The list is given as pairs [val, randomIndex] in list order, where randomIndex is the position of the node that random points to, or null. The answer uses the same format.

Constraints

  • 0 ≤ number of nodes ≤ 1000
  • -10⁴ ≤ Node.val ≤ 10⁴
  • random is either null or points at a node of the same list

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(n)

Time: Two passes over the list, and every map lookup or insert takes constant time on average.

Space: The map holds one entry per node, and the n copies themselves are the output.

Pass 1 makes a copy of every node and remembers it in a map keyed by the original. Pass 2 uses the map to wire the copies: the copy of a node gets next and random equal to the copies of its next and random. Mapping null to null removes every special case.