-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0138_copy_list_with_random_pointer.html
More file actions
649 lines (539 loc) · 23.3 KB
/
0138_copy_list_with_random_pointer.html
File metadata and controls
649 lines (539 loc) · 23.3 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>138 - Copy List with Random Pointer</title>
<link rel="stylesheet" href="styles.css">
<script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
<div class="container">
<div class="problem-info">
<h1><span class="problem-number">#138</span> Copy List with Random Pointer</h1>
<p>
Deep copy a linked list where each node has an additional random pointer.
Uses a hash map to map original nodes to their copies.
</p>
<div class="problem-meta">
<span class="meta-tag">📝 Algorithm</span>
<span class="meta-tag">⏱️ O(n)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0138_copy_list_with_random_pointer/0138_copy_list_with_random_pointer.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>This algorithm solves the problem <strong>step by step</strong>:</p>
<ul>
<li><strong>Understand:</strong> Parse the input data</li>
<li><strong>Process:</strong> Apply the core logic</li>
<li><strong>Optimize:</strong> Use efficient data structures</li>
<li><strong>Return:</strong> Output the computed result</li>
</ul>
</div>
<section class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="controls">
<button id="autoRunBtn" class="btn">▶ Auto Run</button>
<button id="stepBtn" class="btn btn-success">Step</button>
<button id="resetBtn" class="btn btn-danger">Reset</button>
</div>
<div class="status" id="status">Click Auto Run to copy the linked list</div>
<svg id="visualization"></svg>
</section>
<section class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import Optional
"""
LeetCode Copy List with Random Pointer
Problem from LeetCode: https://leetcode.com/problems/copy-list-with-random-pointer/
Description:
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. None of the pointers in the new list should point to nodes in the original list.
For example, if there are two nodes X and Y in the original list, where X.random --> Y, then for the corresponding two nodes x and y in the copied list, x.random --> y.
Return the head of the copied linked list.
The linked list is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val, random_index] where:
- val: an integer representing Node.val
- random_index: the index of the node (range from 0 to n-1) that the random pointer points to, or null if it does not point to any node.
Your code will only be given the head of the original linked list.
Example 1:
Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
Output: [[7,null],[13,0],[11,4],[10,2],[1,0]]
Example 2:
Input: head = [[1,1],[2,1]]
Output: [[1,1],[2,1]]
Example 3:
Input: head = [[3,null],[3,0],[3,null]]
Output: [[3,null],[3,0],[3,null]]
"""
# Definition for a Node.
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
class Solution:
def copyRandomList(self, head: Optional[Node]) -> Optional[Node]:
"""
Make a deep copy of the linked list with random pointers.
Uses a hash map to map original nodes to their copies.
Args:
head: Head of the original linked list
Returns:
Node: Head of the copied linked list
"""
if not head:
return None
# Dictionary to map original nodes to their copies
old_to_new = {}
# First pass: create new nodes
current = head
while current:
old_to_new[current] = Node(current.val)
current = current.next
# Second pass: set pointers
current = head
while current:
# Set next pointer
if current.next:
old_to_new[current].next = old_to_new[current.next]
# Set random pointer
if current.random:
old_to_new[current].random = old_to_new[current.random]
current = current.next
return old_to_new[head]
def copyRandomList_one_pass(self, head: Optional[Node]) -> Optional[Node]:
"""
Make a deep copy of the linked list with random pointers.
Uses a slightly different approach that handles both pointers in one pass.
Args:
head: Head of the original linked list
Returns:
Node: Head of the copied linked list
"""
if not head:
return None
old_to_new = {}
def get_copied_node(node):
"""Get the copied version of a node, creating it if needed."""
if not node:
return None
if node not in old_to_new:
old_to_new[node] = Node(node.val)
return old_to_new[node]
current = head
while current:
# Get or create the copy of the current node
copy = get_copied_node(current)
# Set next pointer
copy.next = get_copied_node(current.next)
# Set random pointer
copy.random = get_copied_node(current.random)
current = current.next
return old_to_new[head]
def copyRandomList_no_extra_space(self, head: Optional[Node]) -> Optional[Node]:
"""
Make a deep copy of the linked list with random pointers.
Uses O(1) extra space by interweaving original and copied nodes.
Args:
head: Head of the original linked list
Returns:
Node: Head of the copied linked list
"""
if not head:
return None
# Step 1: Create a copy of each node and insert it after the original node
current = head
while current:
# Create new node
copy = Node(current.val)
# Insert copy after current
copy.next = current.next
current.next = copy
# Move to next original node
current = copy.next
# Step 2: Set random pointers for the copy nodes
current = head
while current:
# If original has a random pointer, set it for the copy
if current.random:
current.next.random = current.random.next
# Move to next original node
current = current.next.next
# Step 3: Separate the original and copied lists
original = head
copy_head = head.next
copy_current = copy_head
while original:
# Update original's next pointer
original.next = original.next.next
# Update copy's next pointer if there's more nodes
if copy_current.next:
copy_current.next = copy_current.next.next
# Move to next nodes
original = original.next
copy_current = copy_current.next
return copy_head
# Helper function to create a linked list from a list of [val, random_index] pairs
def create_list_from_description(description):
if not description:
return None
# Create nodes
nodes = [Node(val) for val, _ in description]
# Connect next pointers
for i in range(len(nodes) - 1):
nodes[i].next = nodes[i + 1]
# Connect random pointers
for i, (_, random_idx) in enumerate(description):
if random_idx is not None:
nodes[i].random = nodes[random_idx]
return nodes[0] if nodes else None
# Helper function to convert a linked list to a list of [val, random_index] pairs
def list_to_description(head):
if not head:
return []
# Create a list of all nodes
nodes = []
current = head
while current:
nodes.append(current)
current = current.next
# Create description
result = []
current = head
while current:
# Find index of the random node
random_idx = None
if current.random:
random_idx = nodes.index(current.random)
result.append([current.val, random_idx])
current = current.next
return result
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
desc1 = [[7, None], [13, 0], [11, 4], [10, 2], [1, 0]]
head1 = create_list_from_description(desc1)
copy1 = solution.copyRandomList(head1)
result1 = list_to_description(copy1)
print(f"Example 1: {result1}") # Expected output matches input
# Example 2
desc2 = [[1, 1], [2, 1]]
head2 = create_list_from_description(desc2)
copy2 = solution.copyRandomList(head2)
result2 = list_to_description(copy2)
print(f"Example 2: {result2}") # Expected output matches input
# Example 3
desc3 = [[3, None], [3, 0], [3, None]]
head3 = create_list_from_description(desc3)
copy3 = solution.copyRandomList(head3)
result3 = list_to_description(copy3)
print(f"Example 3: {result3}") # Expected output matches input
# Compare different implementations
print("\nUsing no extra space approach:")
copy4 = solution.copyRandomList_no_extra_space(create_list_from_description(desc1))
result4 = list_to_description(copy4)
print(f"Example 1: {result4}")
</pre>
</div>
</section>
</div>
<script>
const width = 900;
const height = 550;
const svg = d3.select("#visualization")
.attr("width", width)
.attr("height", height);
// Original list: [[7,null],[13,0],[11,4],[10,2],[1,0]]
const originalList = [
{ val: 7, randomIdx: null },
{ val: 13, randomIdx: 0 },
{ val: 11, randomIdx: 4 },
{ val: 10, randomIdx: 2 },
{ val: 1, randomIdx: 0 }
];
let copiedList = [];
let phase = 0; // 0: init, 1: creating nodes, 2: setting next, 3: setting random, 4: done
let currentIdx = 0;
let animationTimer = null;
let hashMap = {};
function reset() {
copiedList = [];
phase = 0;
currentIdx = 0;
hashMap = {};
if (animationTimer) clearInterval(animationTimer);
document.getElementById("status").textContent = "Click Auto Run to deep copy the linked list";
render();
}
function render() {
svg.selectAll("*").remove();
const nodeWidth = 60;
const nodeHeight = 40;
const spacing = 120;
// Draw original list
drawList(originalList, 50, 80, "Original List", "#3b82f6", "#dbeafe", true);
// Draw copied list
if (copiedList.length > 0) {
drawList(copiedList, 50, 280, "Copied List", "#10b981", "#d1fae5", false);
}
// Draw hash map
drawHashMap();
// Draw phase indicator
drawPhaseIndicator();
}
function drawList(list, startX, startY, title, strokeColor, fillColor, isOriginal) {
const nodeWidth = 60;
const nodeHeight = 40;
const spacing = 130;
svg.append("text")
.attr("x", startX)
.attr("y", startY - 30)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text(title);
list.forEach((node, idx) => {
const x = startX + idx * spacing;
const y = startY;
const isCurrent = isOriginal && idx === currentIdx && phase > 0 && phase < 4;
// Node box
svg.append("rect")
.attr("x", x)
.attr("y", y)
.attr("width", nodeWidth)
.attr("height", nodeHeight)
.attr("rx", 8)
.attr("fill", isCurrent ? "#fef3c7" : fillColor)
.attr("stroke", isCurrent ? "#f59e0b" : strokeColor)
.attr("stroke-width", isCurrent ? 3 : 2);
// Value
svg.append("text")
.attr("x", x + nodeWidth / 2)
.attr("y", y + 25)
.attr("text-anchor", "middle")
.attr("font-size", "16px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text(node.val);
// Index label
svg.append("text")
.attr("x", x + nodeWidth / 2)
.attr("y", y + nodeHeight + 15)
.attr("text-anchor", "middle")
.attr("font-size", "10px")
.attr("fill", "#64748b")
.text(`[${idx}]`);
// Next pointer (arrow to right)
if (idx < list.length - 1) {
const arrowStartX = x + nodeWidth;
const arrowEndX = x + spacing - 5;
const arrowY = y + nodeHeight / 2;
svg.append("line")
.attr("x1", arrowStartX)
.attr("y1", arrowY)
.attr("x2", arrowEndX - 10)
.attr("y2", arrowY)
.attr("stroke", strokeColor)
.attr("stroke-width", 2)
.attr("marker-end", `url(#arrow-${isOriginal ? 'orig' : 'copy'})`);
}
});
// Draw random pointers
if ((isOriginal && phase >= 3) || (!isOriginal && phase === 4)) {
list.forEach((node, idx) => {
if (node.randomIdx !== null) {
const fromX = startX + idx * spacing + nodeWidth / 2;
const fromY = startY;
const toX = startX + node.randomIdx * spacing + nodeWidth / 2;
const toY = startY + nodeHeight;
// Curved path for random pointer
const midY = fromY - 30 - Math.abs(idx - node.randomIdx) * 10;
svg.append("path")
.attr("d", `M ${fromX} ${fromY} Q ${(fromX + toX) / 2} ${midY} ${toX} ${startY}`)
.attr("fill", "none")
.attr("stroke", "#ef4444")
.attr("stroke-width", 2)
.attr("stroke-dasharray", "5,5")
.attr("marker-end", "url(#arrow-random)");
}
});
}
// Arrow markers
const defs = svg.append("defs");
defs.append("marker")
.attr("id", `arrow-${isOriginal ? 'orig' : 'copy'}`)
.attr("viewBox", "0 0 10 10")
.attr("refX", 9)
.attr("refY", 5)
.attr("markerWidth", 6)
.attr("markerHeight", 6)
.attr("orient", "auto")
.append("path")
.attr("d", "M 0 0 L 10 5 L 0 10 z")
.attr("fill", strokeColor);
defs.append("marker")
.attr("id", "arrow-random")
.attr("viewBox", "0 0 10 10")
.attr("refX", 9)
.attr("refY", 5)
.attr("markerWidth", 6)
.attr("markerHeight", 6)
.attr("orient", "auto")
.append("path")
.attr("d", "M 0 0 L 10 5 L 0 10 z")
.attr("fill", "#ef4444");
}
function drawHashMap() {
const startX = 30;
const startY = 420;
svg.append("text")
.attr("x", startX)
.attr("y", startY)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("Hash Map (old → new):");
Object.entries(hashMap).forEach(([key, value], idx) => {
const x = startX + (idx % 5) * 150;
const y = startY + 20 + Math.floor(idx / 5) * 35;
svg.append("rect")
.attr("x", x)
.attr("y", y)
.attr("width", 140)
.attr("height", 28)
.attr("rx", 5)
.attr("fill", "#e0e7ff")
.attr("stroke", "#6366f1")
.attr("stroke-width", 1);
svg.append("text")
.attr("x", x + 70)
.attr("y", y + 19)
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.attr("fill", "#1e293b")
.text(`Node(${key}) → Node(${value})`);
});
}
function drawPhaseIndicator() {
const phases = [
"Initialize",
"Phase 1: Create new nodes",
"Phase 2: Set next pointers",
"Phase 3: Set random pointers",
"Complete!"
];
const startX = 550;
const startY = 420;
svg.append("text")
.attr("x", startX)
.attr("y", startY)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("Algorithm Steps:");
phases.forEach((p, idx) => {
const y = startY + 25 + idx * 25;
const isCurrent = idx === phase;
const isComplete = idx < phase;
svg.append("circle")
.attr("cx", startX + 10)
.attr("cy", y - 4)
.attr("r", 6)
.attr("fill", () => {
if (isComplete) return "#10b981";
if (isCurrent) return "#f59e0b";
return "#e2e8f0";
});
svg.append("text")
.attr("x", startX + 25)
.attr("y", y)
.attr("font-size", "12px")
.attr("font-weight", isCurrent ? "bold" : "normal")
.attr("fill", isCurrent ? "#f59e0b" : (isComplete ? "#10b981" : "#64748b"))
.text(p);
});
}
function step() {
if (phase === 4) {
document.getElementById("status").textContent = "✓ Deep copy complete!";
return;
}
if (phase === 0) {
phase = 1;
currentIdx = 0;
document.getElementById("status").textContent = "Phase 1: Creating new nodes and building hash map";
} else if (phase === 1) {
// Create new nodes
if (currentIdx < originalList.length) {
const node = originalList[currentIdx];
copiedList.push({ val: node.val, randomIdx: null });
hashMap[node.val] = node.val;
document.getElementById("status").textContent =
`Created copy of Node(${node.val}), added to hash map`;
currentIdx++;
} else {
phase = 2;
currentIdx = 0;
document.getElementById("status").textContent =
"Phase 2: Setting next pointers (using hash map)";
}
} else if (phase === 2) {
// Set next pointers (simulated - they're already connected)
if (currentIdx < originalList.length) {
const node = originalList[currentIdx];
document.getElementById("status").textContent =
`Set copy(${node.val}).next → ${currentIdx < originalList.length - 1 ? `copy(${originalList[currentIdx + 1].val})` : 'null'}`;
currentIdx++;
} else {
phase = 3;
currentIdx = 0;
document.getElementById("status").textContent =
"Phase 3: Setting random pointers";
}
} else if (phase === 3) {
// Set random pointers
if (currentIdx < originalList.length) {
const node = originalList[currentIdx];
copiedList[currentIdx].randomIdx = node.randomIdx;
const randomTarget = node.randomIdx !== null ? `copy(${originalList[node.randomIdx].val})` : 'null';
document.getElementById("status").textContent =
`Set copy(${node.val}).random → ${randomTarget}`;
currentIdx++;
} else {
phase = 4;
document.getElementById("status").textContent =
"✓ Deep copy complete! All pointers correctly set.";
}
}
render();
}
function autoRun() {
if (animationTimer) {
clearInterval(animationTimer);
animationTimer = null;
document.getElementById("autoRunBtn").textContent = "▶ Auto Run";
return;
}
document.getElementById("autoRunBtn").textContent = "⏸ Pause";
animationTimer = setInterval(() => {
if (phase === 4) {
clearInterval(animationTimer);
animationTimer = null;
document.getElementById("autoRunBtn").textContent = "▶ Auto Run";
return;
}
step();
}, 800);
}
document.getElementById("autoRunBtn").addEventListener("click", autoRun);
document.getElementById("stepBtn").addEventListener("click", step);
document.getElementById("resetBtn").addEventListener("click", reset);
reset();
</script>
</body>
</html>