Python 0138.py
class Solution:
def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
if not head:
return None
# inject IDs
id = 0
current = head
while current:
current.id = id
id += 1
current = current.next
all = []
for _ in range(id):
all.append(Node(0, None, None))
# replicate
id = 0
current = head
while current:
all[id].val = current.val
if id < len(all) - 1:
all[id].next = all[id + 1]
if current.random:
all[id].random = all[current.random.id]
current = current.next
id += 1
return all[0]
Difficulty
and has an acceptance rate of about 63% (3+ million submissions).
Typical patterns to solve this problem:
- Hash Table
- Linked List
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation creates a deep copy of a singly-linked list where each node contains an additional random pointer that may reference any node in the list or be None. The algorithm proceeds in three conceptual phases: a preliminary pass that annotates each original node with a unique identifier, allocation of a parallel array of new nodes, and a second pass that transfers values and reconstructs both the next and random links. By using an auxiliary array indexed by the injected identifiers, the method resolves random references in constant time during the second traversal.
Phase 1 - Injecting identifiers
The first loop walks the original list from the head, assigning a monotonically increasing integer to a newly created attribute id on each node. This identifier serves as a stable key that can later be used to locate the corresponding copy in the auxiliary array.
if not head:
return None
id = 0
current = head
while current:
current.id = id
id += 1
current = current.next
The guard if not head: handles the edge case where the input list is empty, returning None immediately without further processing.
Phase 2 - Pre-allocating the copy nodes
After the identifier injection, the total number of nodes is known (id). An array named all is created with that exact length, and each slot is filled with a freshly instantiated node whose fields are initially placeholders (val=0, next=None, random=None). This pre-allocation avoids repeated node creation inside the main copy loop and guarantees that each index in the array corresponds to a unique node in the new list.
all = []
for _ in range(id):
all.append(Node(0, None, None))
The use of a simple list comprehension-style loop ensures that the allocation cost is proportional to the number of original nodes and that the memory layout is contiguous, which can improve cache locality when the array is accessed repeatedly in the next phase.
Phase 3 - Replicating values and wiring pointers
A second traversal of the original list copies the payload (val) into the matching node in all. The next pointer of each new node is set to the subsequent element in the array, except for the final node where no forward link is required. For the random pointer, the algorithm checks whether the original node’s random field is non-null; if it is, the previously stored identifier (current.random.id) is used to fetch the appropriate copy from all. This direct indexing eliminates the need for a hash map or additional search.
id = 0
current = head
while current:
all[id].val = current.val
if id < len(all) - 1:
all[id].next = all[id + 1]
if current.random:
all[id].random = all[current.random.id]
current = current.next
id += 1
The conditional if current.random: safeguards against dereferencing a None random pointer, thereby correctly handling nodes whose random reference is absent. The boundary check if id < len(all) - 1: prevents an out-of-range assignment for the tail node’s next field.
Return value
After the replication loop finishes, the head of the newly constructed list resides at index 0 of the auxiliary array. The method returns this reference, delivering a fully independent copy whose structure mirrors the original, including all next and random relationships.
return all[0]
Edge-case handling
The algorithm explicitly addresses two important edge conditions. First, an empty input list triggers an early return of None, ensuring that no further work is performed and that the caller receives a correctly typed empty result. Second, nodes whose random pointer is None are left with a None random reference in the copy, because the conditional guard prevents any attempt to resolve a non-existent identifier.
Performance-related choices
The design avoids multiple passes over the list for mapping purposes. By embedding a numeric identifier directly onto each original node, the code eliminates the need for an external dictionary that would otherwise map original nodes to their copies. This in-place tagging reduces auxiliary memory overhead to the size of the identifier field, which is negligible compared to the array of new nodes.
Pre-allocating the entire array of copy nodes before populating fields means that each node is created exactly once, and subsequent field assignments are simple attribute writes. This approach benefits from predictable memory allocation patterns and improves data locality, as the array elements are stored contiguously in memory. The direct index-based lookup for random pointers yields constant-time resolution, avoiding the logarithmic or linear costs associated with search-based strategies.
Overall, the implementation achieves a linear traversal count (two passes) and leverages straightforward data structures to keep the runtime efficient while maintaining clear and deterministic behavior across all supported input configurations.
ELI5 - Simplified Explanation
Imagine a line of friends holding hands, where each friend has a special note and sometimes points to another friend further down the line. To make an exact copy, the first step is to walk down the line and give every friend a unique number tag so everyone can be identified easily.
Once every friend has a numbered tag, a brand new line of empty copies is built, one for each original friend. Now, the process happens again by walking through the original line once more. For each original friend, the corresponding copy is found using the number tag. The copied friend is given the same note, told which friend is next in line, and shown which friend they should point to based on the random connection from the original. By the time the walk is finished, there is a perfect second line of friends that looks and acts just like the first one.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | Java | C# | JS | Go | TS | ||||
| LeetcodeHelp | C++ | Python | Java | ||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||
| Progiez | C++ | Python | Java | ||||||||
| github | begeekmyfriend | C | |||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++ | ||||||||||
| bujosa | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| chenyanzhe | C++ | ||||||||||
| Dijkstra-Edu | Java | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| FelixFan1122 | C# | ||||||||||
| fengvyi | C++ | ||||||||||
| fpdjsns | C++ | ||||||||||
| gaosq0604 | Python | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lennylxx | C | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| luangong | C++ | ||||||||||
| MacJim | C++ | ||||||||||
| qiyuangong | Python | ||||||||||
| shreymehul | C# | ||||||||||
| sonugiri1043 | C++ | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| XiaotaoGuo | C++ | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, C#, Go, Java, JavaScript, Python, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| begeekmyfriend | C | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| bujosa | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| chenyanzhe | C++ | ||||||||||
| Dijkstra-Edu | Java | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| FelixFan1122 | C# | ||||||||||
| fengvyi | C++ | ||||||||||
| fpdjsns | C++ | ||||||||||
| gaosq0604 | Python | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lennylxx | C | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| luangong | C++ | ||||||||||
| MacJim | C++ | ||||||||||
| qiyuangong | Python | ||||||||||
| shreymehul | C# | ||||||||||
| sonugiri1043 | C++ | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| XiaotaoGuo | C++ | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 133: Clone Graph
- problem 1485: Clone Binary Tree With Random Pointer
- problem 1490: Clone N-ary Tree
Solved On The Same Day
- problem 110: Balanced Binary Tree
- problem 111: Minimum Depth of Binary Tree
- problem 118: Pascal's Triangle
- problem 119: Pascal's Triangle II
- problem 228: Summary Ranges
- problem 530: Minimum Absolute Difference in BST
- problem 82: Remove Duplicates from Sorted List II
- problem 102: Binary Tree Level Order Traversal
- problem 103: Binary Tree Zigzag Level Order Traversal
- problem 105: Construct Binary Tree from Preorder and Inorder Traversal
- problem 106: Construct Binary Tree from Inorder and Postorder Traversal
- problem 107: Binary Tree Level Order Traversal II
- problem 109: Convert Sorted List to Binary Search Tree
- problem 117: Populating Next Right Pointers in Each Node II
- problem 128: Longest Consecutive Sequence
- problem 150: Evaluate Reverse Polish Notation
- problem 155: Min Stack
- problem 209: Minimum Size Subarray Sum
- problem 274: H-Index
- problem 380: Insert Delete GetRandom O(1)
- problem 427: Construct Quad Tree
- problem 452: Minimum Number of Arrows to Burst Balloons
- problem 30: Substring with Concatenation of All Words
- problem 37: Sudoku Solver
- problem 44: Wildcard Matching
- problem 1326: Minimum Number of Taps to Open to Water a Garden
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality