-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCopy List with Random Pointer.java
More file actions
66 lines (53 loc) · 1.67 KB
/
Copy List with Random Pointer.java
File metadata and controls
66 lines (53 loc) · 1.67 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
// https://leetcode.com/problems/copy-list-with-random-pointer/
/*
// Definition for a Node.
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
*/
/*
Time Complexity: O(n) where n = length of original linked list. The original linked list is being iterated 2 times.
Space Complexity: O(k) where k = # of keys inside Hash Map.
Thought Process:
- Create a map where key = oldNode, value = newNode
- Iterate original linked list
- while iterating,
- Create a deepy copy of existing node
- Insert old node and new node to map
- Create a dummy node and reference to head of new linked list
- Iterate old linked list again
- Upon every iteration, fetch new node and update its next and random pointer
- Return head of new linked list
*/
class Solution {
public Node copyRandomList(Node head) {
Map<Node, Node> nodeMap = new HashMap<>();
Node curNode = head;
while (curNode != null) {
Node newNode = new Node(curNode.val);
nodeMap.put(curNode, newNode);
curNode = curNode.next;
}
Node dummyNode = new Node(0);
dummyNode.next = nodeMap.get(head);
curNode = head;
while (curNode != null) {
Node newNode = nodeMap.get(curNode);
if (curNode.next != null) {
newNode.next = nodeMap.get(curNode.next);
}
if (curNode.random != null) {
newNode.random = nodeMap.get(curNode.random);
}
curNode = curNode.next;
}
return dummyNode.next;
}
}