Copy List with Random Pointer
The key idea
random pointer: when you copy a node you may not have created its random target yet. Either remember the original->copy mapping in a hash map, or weave each copy in right after its original so the target copy is always reachable as original.random.next.Problem
You are given a linked list of length n, where each node holds a val and two pointers: a normal next pointer and an extra random pointer that may point to any node in the list or to null.
Build a deep copy of the list. The copy must be made of brand-new nodes, each with the same val, where both the next and the random pointers of the new nodes point only to nodes within the copied list (never to a node in the original list).
For example, if a node in the original list points its random at the node with index 7, then the corresponding new node's random must point at the new node with index 7. Return the head of the copied list. None of the new nodes' pointers may reference the original list, and none of the original list's pointers may be changed.
Constraints
0 <= n <= 1000-10^4 <= Node.val <= 10^4Node.randomisnullor points to some node in the linked list.
Examples
Complexity
Time: O(n) Space: O(1)
See the full solution
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization
More Linked List problems
- Add Two NumbersMEDIUM
- Design Linked ListMEDIUM
- Insert Greatest Common Divisors in Linked ListMEDIUM
- Intersection of Two Linked ListsEASY
- Maximum Twin Sum of a Linked ListMEDIUM
- Merge Two Sorted ListsEASY
- Odd Even Linked ListMEDIUM
- Partition ListMEDIUM
- Remove Duplicates from Sorted List IIMEDIUM
- Remove Linked List ElementsEASY
- Remove Nth Node From End of ListMEDIUM
- Reorder ListMEDIUM