forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcopy_random_pointer.py
More file actions
83 lines (65 loc) · 2.29 KB
/
copy_random_pointer.py
File metadata and controls
83 lines (65 loc) · 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
"""
Copy List with Random Pointer
Given a linked list where each node contains an additional random pointer that
could point to any node in the list or null, return a deep copy of the list.
Reference: https://leetcode.com/problems/copy-list-with-random-pointer/
Complexity:
Time: O(n)
Space: O(n)
"""
from __future__ import annotations
from collections import defaultdict
class RandomListNode:
"""Node with next and random pointers for deep-copy problem."""
def __init__(self, label: int) -> None:
self.label = label
self.next: RandomListNode | None = None
self.random: RandomListNode | None = None
def copy_random_pointer_v1(head: RandomListNode | None) -> RandomListNode | None:
"""Deep-copy a linked list with random pointers using a dictionary.
Args:
head: Head of the original list.
Returns:
Head of the deep-copied list.
Examples:
>>> node = RandomListNode(1)
>>> node.random = node
>>> copied = copy_random_pointer_v1(node)
>>> copied.label == 1 and copied.random is copied
True
"""
node_map: dict[RandomListNode, RandomListNode] = {}
current = head
while current:
node_map[current] = RandomListNode(current.label)
current = current.next
current = head
while current:
node_map[current].next = node_map.get(current.next)
node_map[current].random = node_map.get(current.random)
current = current.next
return node_map.get(head)
def copy_random_pointer_v2(head: RandomListNode | None) -> RandomListNode | None:
"""Deep-copy a linked list with random pointers using defaultdict.
Args:
head: Head of the original list.
Returns:
Head of the deep-copied list.
Examples:
>>> node = RandomListNode(1)
>>> node.random = node
>>> copied = copy_random_pointer_v2(node)
>>> copied.label == 1 and copied.random is copied
True
"""
copy: defaultdict[RandomListNode | None, RandomListNode | None] = defaultdict(
lambda: RandomListNode(0)
)
copy[None] = None
node = head
while node:
copy[node].label = node.label
copy[node].next = copy[node.next]
copy[node].random = copy[node.random]
node = node.next
return copy[head]