Copy List with Random Pointer

Medium#138old node → new

You get a linked list where every node has, besides next, a link called random to any node of the same list or to none. Make a full copy: new nodes with the same values, and every link of the copy goes to a new node, never to an old one. Our example: 3 → 8 → 5 → 1, random 3 → 5, 8 → 3, 5 → none, 1 → 1 (itself).

input
head: the head of a linked list, or null for an empty one; each node also has random, a pointer to any node of the list or null. The tests write the list as LeetCode does: [val, random’s index] per node, null for no random.
returns
The head of a deep copy: new nodes with the same values, whose next and random point to the copy’s own nodes as the input’s point to the input’s. No node of the copy may be a node of the input, and the input must stay as it came.
constraints
  • 0 ≤ the number of nodes ≤ 500
  • −10⁴ ≤ Node.val ≤ 10⁴
  • random is null or the index of a node of the list
our 11 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * // Definition for a _Node.
 * function _Node(val, next, random) {
 *    this.val = val;
 *    this.next = next;
 *    this.random = random;
 * };
 */

/**
 * @param {_Node} head
 * @return {_Node}
 */
function copyRandomList(head) {

}
Ctrl ↵
format
reset

saved in this browser

11 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more hash map problems

Pattern “Hash map” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.