Clone list with random pointers
Company: Meta
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Overview: Meta software-engineer technical-screen coding question: deep-copy a singly linked list whose nodes carry an arbitrary random pointer (which may be null, point backward, or form cycles). It tests both the O(n)-space hash-map solution and the O(1)-auxiliary-space in-place weaving technique, plus reasoning about pointer integrity, cycle safety, and verifying the copy is structurally equal to and isolated from the original.
Constraints
- 0 <= number of nodes <= 1000
- -10000 <= node value <= 10000
- random_index is either null (no random pointer) or a valid 0-based index into the list
- random pointers may point backward, forward, to the same node (self), or form cycles
- The returned copy must be fully isolated: no copied node's next/random may reference an original node
Examples
Input: ([[7, None], [13, 0], [11, 4], [10, 2], [1, 0]],)
Expected Output: [[7, None], [13, 0], [11, 4], [10, 2], [1, 0]]
Explanation: Canonical LeetCode-138 example: 5 nodes with assorted backward/forward random links. The deep copy must serialize to the identical array, proving every next and random link was reproduced among the new nodes.
Input: ([[1, 1], [2, 1]],)
Expected Output: [[1, 1], [2, 1]]
Explanation: Two nodes where both random pointers target node 1. Tests that multiple originals can share a random target and the copy preserves that aliasing among clones.
Hints
- First pass: create a clone for every original node and store the mapping original-node -> clone in a hash map. Second pass: for each original node, set clone.next = map[orig.next] and clone.random = map[orig.random], letting null map to null.
- Never *follow* a random pointer while constructing the copy — only look it up in the map. That is exactly why random cycles or self-references can never cause an infinite loop or a double-clone.
- For O(1) auxiliary space, weave each clone directly after its original (A -> A' -> B -> B' -> ...). Then clone.random is simply orig.random.next, and a final unweaving pass restores the original list and extracts the copy.
- Watch the corner cases: an empty list returns an empty result, and a single node whose random points to itself must serialize with random_index 0.