Copy List With Random Pointer
Detailed guide and Python implementation for the 'Copy List With Random Pointer' problem.
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 input structures
- Single element inputs
- Large numerical bounds
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Lists
Learn everything about Python lists. Discover how to create, slice, modify, and iterate through arrays in Python natively.
How to Sort a List in Python
Learn how to sort a list in Python using the sort() method and the sorted() function. Discover custom key sorting and reverse order examples.
Python List Methods
Quick reference guide for Python list operations. Master appending, inserting, removing, sorting, and slicing elements.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.