Skip to problem
←

Copy List with Random Pointer

Medium 0 attempts

You're given a linked list in which every node carries, besides its usual next pointer, an extra random pointer that can point to any node in the list or to nothing at all. Build a completely independent deep copy of this list, matching the same structure.

Return the copied head, or null for an empty list. Allocate new nodes: neither next nor random in the copy may point into the original list. The original list must have its values and links unchanged when your function returns.

Function contract

Implement copyRandomList(head). The runner builds nodes with val, next, and random fields from [value, randomIndex] pairs. randomIndex is zero-based; null means no random pointer. An empty array becomes null.

Output: The head of a new, independent list preserving values and next/random relationships. Restore the original list before returning. No copied pointer may refer to an original node.

Example 1

Input
head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
Output
[[7,null],[13,0],[11,4],[10,2],[1,0]]

Example 2

Input
head = []
Output
[]
Visual Aid
Same structure, separate nodes
Original713random → first nodeCopy713random → first node

For [[7,null],[13,0]], solid arrows are next links and dashed arrows are random links. The copied nodes share no identity with the original nodes.

Constraints
  • 0 <= n <= 1000
  • -10^4 <= Node.val <= 10^4
  • random is null or points to a node in the list
Topics

Interleave + Separate

Insert cloned nodes after originals, set random pointers, then separate.

javascript
function copyRandomList(head) {
  if (!head) return null;
  let curr = head;
  while (curr) {
    const clone = {val: curr.val, next: curr.next, random: null};
    curr.next = clone; curr = clone.next;
  }
  curr = head;
  while (curr) { if (curr.random) curr.next.random = curr.random.next; curr = curr.next.next; }
  const dummy = {next: null}; let tail = dummy; curr = head;
  while (curr) {
    tail.next = curr.next; tail = tail.next;
    curr.next = curr.next.next; curr = curr.next;
  }
  return dummy.next;
}

Time: O(n) | Space: O(1) auxiliary space, excluding O(n) newly allocated output nodes. The separation pass restores the original next links.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript