Deep Copy a Linked List With Arbitrary Cross References
Last updated: November 29, 2026
Quick Overview
Each node in a singly linked list has a next pointer and a random pointer that may point to any node in the list or be null. Return a deep copy whose pointers reference only new nodes, ideally with O(1) extra space.
Microsoft
November 29, 20260
0
0 solved
Each node in a singly linked list has a next pointer and a random pointer that may point to any node in the list or be null. Return a deep copy whose pointers reference only new nodes, ideally with O(1) extra space.
Microsoft engineers working on document models in Word, OneNote, or Visual Studio deal with object graphs that contain back references, and copying them correctly is a real task. The interviewer usually accepts the hash-map version first and then pushes for the interleaving trick to see pointer manipulation under pressure.
What the Interviewer Expects
- Gives the O(n) hash map solution quickly
- Moves to the interleaving approach for O(1) extra space
- Restores the original list after copying
- Handles random pointers that are null or point to self
- Explains how this generalizes to cloning arbitrary graphs
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- How would you clone a general graph where nodes have a list of neighbors?
- The list may be shared by other threads while you copy: what breaks with the interleaving approach?
- How would you serialize this structure to disk and rebuild it?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Return the head of a new list with the same values, the same next order, and random pointers that point to the corresponding new nodes. The original must be unchanged when we return. Target O(n) t...
High-Level Design
The straightforward version is two passes with a dict from old node to new node: create all copies, then set next and random through the map. To drop the map, I store the mapping in the list itsel...