As reported: DigitalOcean SWE II, round 2 with a senior engineer (May 2025): behavioral questions, then clone a linked list whose nodes have
nextandrandompointers. Follow-up on space optimization and the time complexity.
A linked list of length n is given where each node has a val, a next pointer and a random pointer that points to any node in the list or is null. Return a deep copy of the list: n brand-new nodes where each new node's next and random point to new nodes, so that the copy represents the same list state. No pointer in the copy may point to a node of the original list, and the original list must be left unchanged.
This is LeetCode 138 — Copy List with Random Pointer.
The list is written as n pairs [val, random_index], where random_index is the 0-based position of the node random points to, or null.
Example 1
head = [[7,null],[13,0],[11,4],[10,2],[1,0]] -> [[7,null],[13,0],[11,4],[10,2],[1,0]]
Example 2
head = [[1,1],[2,1]] -> [[1,1],[2,1]]
Example 3
head = [[3,null],[3,0],[3,null]] -> [[3,null],[3,0],[3,null]]
Example 4
head = [] -> []
Constraints: 0 ≤ n ≤ 1000; -10^4 ≤ Node.val ≤ 10^4; random is null or points to a node in the list.
Follow-up: reduce the extra space to O(1) (not counting the copy itself).
Code runner format: one line, the list as a JSON array of [val, random_index] pairs. Implement copyRandomList(head) with the given Node class; the harness checks that the copy shares no node with the original and that the original is unchanged, then prints the copy in the same format.