Clone list with random pointers
MetaSoftware Engineer · Technical ScreenLast updated
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.
Question
You are given the head of a singly linked list where each node has two pointers: next and random. The random pointer may be null or point to any node in the list (including itself). Construct a deep copy of the list and return the head of the copy. The copied list must consist of brand-new nodes, and each copied node's next/random must point to the corresponding copied node, never to a node in the original list.
- Core deep copy. Build a deep copy in O(n) time. Walk through the original once and reproduce both the
nextchain and the arbitraryrandomlinks among the new nodes. - Hash-map approach. Explain the straightforward solution that uses a map from each original node to its clone, then a second pass to wire up
nextandrandom. State its O(n) time and O(n) auxiliary space. - In-place weaving approach. Explain the interleaving (weave/unweave) technique that achieves O(1) auxiliary space beyond the new nodes: clone each node and splice it directly after its original (
A -> A' -> B -> B' -> ...), assign each clone'srandomfromorig.random.next, then unweave the two lists to restore the original and extract the copy. - Handling cycles in random pointers. Discuss why the algorithm stays correct when
randompointers form cycles or point backward (you copy links, not by traversal order, so cycles never cause infinite loops or re-cloning). - Verifying correctness. Describe how you verify structural equality of the copy against the original: same length, equal node values in order, the
randomof each copied node maps to the correct relative position, and that no copied pointer escapes into the original list (deep-copy isolation). - Corner cases. Make sure the solution handles an empty list, a single-node list (including a node whose
randompoints to itself), and a list where everyrandomisnull.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.