Copy List With Random Pointer
Learn how to solve the 'Copy List With Random Pointer' problem. This detailed resource details brute force and optimized approaches.
Problem Statement
A linked list of length n is given such that each node contains an additional random pointer, which could point to any node in the list, or null.
Construct a deep copy of the list. The deep copy should consist of exactly n brand new nodes, where each new node has its value set to the value of its corresponding original node. Both the next and random pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state.
The list is represented as a list of pairs [val, random_index] where random_index is the index of the node the random pointer points to, or -1 if it points to null. Implement a function copyRandomList(head: list) -> list that returns the deep copy in the same format.
- •0 <= n <= 1000
- •-10000 <= Node.val <= 10000
- •Node.random is null or points to some node in the linked list
Examples
[[7,-1],[13,0],[11,4],[10,2],[1,0]]
[[7,-1],[13,0],[11,4],[10,2],[1,0]]
The deep copy has the same structure. Node 0 (val=7) has random=null, Node 1 (val=13) has random pointing to Node 0, etc.
[[1,1],[2,1]]
[[1,1],[2,1]]
Node 0 (val=1) has random pointing to Node 1. Node 1 (val=2) has random pointing to Node 1 (itself).
[[3,-1],[3,0],[3,-1]]
[[3,-1],[3,0],[3,-1]]
Three nodes all with value 3. Node 1's random points to Node 0.
Need a Hint?
Edge Cases to Watch
- Empty list or null input variables
- Single item lists/arrays
- Extremely large input bounds causing integer or stack overflow
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.