forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0138-copy-list-with-random-pointer.js
More file actions
71 lines (58 loc) · 1.57 KB
/
0138-copy-list-with-random-pointer.js
File metadata and controls
71 lines (58 loc) · 1.57 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
/**
* https://leetcode.com/problems/copy-list-with-random-pointer/
* Time O(N) | Space O(N)
* @param {Node} head
* @return {Node}
*/
var copyRandomList = function (head, map = new Map()) {
if (!head) return null;
if (map.has(head)) return map.get(head);
const clone = new Node(head.val);
map.set(head, clone); /* | Space O(N) */
clone.next = copyRandomList(head.next, map); /* Time O(N) | Space O(N) */
clone.random = copyRandomList(
head.random,
map,
); /* Time O(N) | Space O(N) */
return clone;
};
/**
* https://leetcode.com/problems/copy-list-with-random-pointer/
* Time O(N) | Space O(1)
* @param {Node} head
* @return {Node}
*/
var copyRandomList = function (head) {
if (!head) return null;
cloneNode(head); /* Time O(N) */
connectRandomNode(head); /* Time O(N) */
return connectNode(head); /* Time O(N) */
};
const cloneNode = (curr) => {
while (curr) {
/* Time O(N) */
const node = new Node(curr.val);
node.next = curr.next;
curr.next = node;
curr = node.next;
}
return curr;
};
const connectRandomNode = (curr) => {
while (curr) {
/* Time O(N) */
curr.next.random = curr.random?.next || null;
curr = curr.next.next;
}
};
const connectNode = (head) => {
let [prev, curr, next] = [head, head.next, head.next];
while (prev) {
/* Time O(N) */
prev.next = prev.next.next;
curr.next = curr?.next?.next || null;
prev = prev.next;
curr = curr.next;
}
return next;
};