InterviewPrepKit

Home / Coding / Linked List

Copy List with Random Pointer

medium Original ↗
Solving tips
  • The core difficulty is translating 'pointer to original node X' into 'pointer to clone of X'; a hash map keyed on node identity is that translation.
  • Two passes: pass 1 creates all clones into the map, pass 2 wires next and random via lookups (by then every target's clone exists); seed the map with {None: None} to avoid null checks.
  • Key on node IDENTITY, not value: duplicate values must map to distinct clones.
  • O(n) time, O(n) space for the map; for O(1) extra space, interleave each clone after its original so clone = original.next, wire randoms, then unzip (restore the input).

Problem

You are given a linked list whose nodes carry an extra pointer: besides next, each node has a random pointer that may point to any node in the list — or to nothing (None).

Build and return a deep copy of the list: exactly as many brand-new nodes, with the same values, whose next and random pointers reproduce the original’s shape entirely within the new nodes. No pointer in the copy may reference an original node, and vice versa.

Examples

Notation: [val, random_index] where random_index is the position of the node the random pointer targets (or null).

  • Input: [[7,null],[13,0],[11,4],[10,2],[1,0]] → Output: [[7,null],[13,0],[11,4],[10,2],[1,0]] A structurally identical list of five fresh nodes; e.g. the copy of 13 has its random aimed at the copy of 7.
  • Input: [[1,1],[2,1]] → Output: [[1,1],[2,1]] Both randoms point at the second node — including the second node pointing at itself.
  • Input: [[3,null],[3,0],[3,null]] → Output: [[3,null],[3,0],[3,null]] Duplicate values are fine; identity, not value, is what must be mirrored.

Constraints

  • Number of nodes is in [0, 1000].
  • -10^4 <= Node.val <= 10^4
  • random is None or points at a node of the same list.

Think about it first

Hint 1 Copying val and next is a plain walk. The hard part: when you copy a node, the node its random points at may not have been copied yet. How do you translate "original node X" into "copy of X"?
Hint 2 A dictionary mapping original node → its clone answers that translation in O(1). Two passes: first create all clones, then wire every clone's next and random through the map.
Hint 3 To do it with O(1) extra space: splice each clone right after its original (A -> A' -> B -> B' -> ...). Then original.random.next is the clone's random target. A third pass unzips the two lists.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.