Imagine you have a special linked list where each node not only points to the next node, but also has a random pointer that can point to any node in the list (or be null). Your task is to create a deep copy of this entire structure.
A deep copy means creating completely new nodes with the same values, where:
- Each new node's
nextpointer points to the corresponding new node - Each new node's
randompointer points to the corresponding new node - No pointers in the new list should reference the original list
For example, if the original list has nodes X and Y where X.random โ Y, then in your copied list with nodes x and y, we should have x.random โ y.
Input: Head of the original linked list
Output: Head of the deep copied linked list
Note: The problem description shows the list as [val, random_index] pairs for clarity, but your function only receives the head node.
Input & Output
Visualization
Time & Space Complexity
Single pass through the list, hash map operations are O(1) on average
Hash map stores mapping for all n nodes
Constraints
- 0 โค n โค 1000
- -104 โค Node.val โค 104
- Node.random is null or is pointing to some node in the linked list
- You must return the copy of the given head as a reference to the cloned list