1. Original → clone
Map each original node to its fresh copy.
const clones = new Map()Typorithm · medium
Step 1 of 8 · intro card
Linked Lists
Two passes: first create every clone in a Map keyed by the original, then wire each clone's next and random via map lookups.
Each node has a random pointer that may target any node, so links cannot be wired in a single forward pass.
First pass: create a clone for every node and store original → clone in a Map.
Second pass: set each clone's next and random by looking up the originals' clones.
Map keyed by the original node.
Pass 1 creates shells, pass 2 wires.
next and random map identically.
function copyRandomList(head) {
if (head === null) {
return null;
}
const clones = new Map();
let curr = head;
while (curr !== null) {
clones.set(curr, { val: curr.val, next: null, random: null });
curr = curr.next;
}
curr = head;
while (curr !== null) {
const clone = clones.get(curr);
clone.next = curr.next === null ? null : clones.get(curr.next);
clone.random = curr.random === null ? null : clones.get(curr.random);
curr = curr.next;
}
return clones.get(head);
}Connect each part of the code to the concept before you type.
Map each original node to its fresh copy.
const clones = new Map()The first pass creates every clone with null links.
clones.set(curr, { val: curr.val, next: null, random: null })Look up the clone of the original's next node.
clone.next = curr.next === null ? null : clones.get(curr.next)The random pointer maps the same way as next.
clone.random = curr.random === null ? null : clones.get(curr.random)Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.