The Copy List with Random Pointer interview question is a classic linked list problem. You are given a linked list where each node has a next pointer and an additional random pointer that can point to any node in the list or be null. You must return a deep copy of the entire list. A deep copy means you must create entirely new nodes, and their random pointers must point to the new nodes in the copied list, not the original nodes.
This is one of the most popular Linked List interview patterns, asked by Amazon, Microsoft, and Meta. It tests your ability to handle complex pointer structures and memory mapping. It evaluates whether you can keep track of the relationship between original and copied nodes, typically using a hash map or a clever in-place interleaving technique.
There are two main approaches:
Map<OriginalNode, CopiedNode>. Traverse again to set the next and random pointers using the map.A -> A' -> B -> B').random pointers of the new nodes (A'.random = A.random.next).List: 1 -> 2, where 1.random = 2 and 2.random = 1.
Using Hash Table:
{1: 1', 2: 2'}.1': next = 2', random = 2'.2': next = null, random = 1'.
Using Interleaving:1 -> 1' -> 2 -> 2'.1'.random = 1.random.next = 2.next = 2'.1' -> 2'.random pointer of a new node back to an original node.random pointer is null.| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Remove Zero Sum Consecutive Nodes from Linked List | Medium | Solve | |
| Remove Duplicates From an Unsorted Linked List | Medium | Solve | |
| Linked List Cycle II | Medium | Solve | |
| Delete Nodes From Linked List Present in Array | Medium | Solve | |
| Linked List Components | Medium | Solve |