Deep-Copy a Linked List Whose Nodes Carry Random Pointers, in C
Company: Amazon
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Technical Screen
Each node of a singly linked list holds an integer value, a `next` pointer to the following node, and a `random` pointer that may point to any node of the same list or be null. Write a function that makes a deep copy of the list: a new list of freshly allocated nodes with the same values, in which every copied node's `next` and `random` pointers refer to the corresponding copied nodes, never to nodes of the original list. When the function returns, the original list must be unchanged.
This version assumes C, the usual language for a firmware role, and this node structure:
```c
struct Node {
int val;
struct Node *next;
struct Node *random;
};
struct Node *copy_random_list(struct Node *head);
```
```hint Find the copy of any node
The `random` pointer is the hard part. While copying, ask how you would find, for an arbitrary original node, the copy that stands for it.
```
```hint Without a lookup table
If memory for a table is not allowed, ask where in the existing list structure you could keep the link from each original node to its copy for a while.
```
### Clarifying Questions
- Can a `random` pointer be null, and can it point to its own node?
- May the function modify the original list temporarily if it restores it before returning?
- Is extra memory proportional to the list length acceptable, or must the memory used beyond the new nodes be constant?
- What should happen if allocating a node fails partway through the copy?
### What a Strong Answer Covers
- A correct deep copy in which no copied pointer refers to an original node
- A way to map each original node to its copy, and what that mapping costs
- A constant-extra-memory method that restores the original list exactly
- Edge cases: an empty list, null random pointers, a node whose random pointer is itself, random pointers to earlier and to later nodes
- Allocation failure: freeing a partial copy and leaving the original intact
- Time and memory complexity of each approach
### Follow-up Questions
- How would you test that the copy is deep, so that no pointer in it refers to an original node?
- How would your approach change if the `next` pointers could form a cycle?
- The firmware has no heap, only a fixed pool of preallocated nodes. How do you adapt the copy?
- Another task may read the original list while you copy it. Is your method still safe?
Overview: A linked-list question that asks for a deep copy of a list whose nodes carry both a next pointer and a random pointer to any node or null. It tests mapping each original node to its copy, doing so with constant extra memory, restoring the original list, and handling allocation failure in C.