-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0141_linked_list_cycle.html
More file actions
489 lines (413 loc) Β· 17.9 KB
/
0141_linked_list_cycle.html
File metadata and controls
489 lines (413 loc) Β· 17.9 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LC 141: Linked List Cycle - Algorithm Visualization</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">#141</span> Linked List Cycle</h1>
<p>Given the head of a linked list, determine if there is a cycle in it. A cycle exists if some node can be reached again by following the next pointers.</p>
<div class="problem-meta">
<span class="meta-tag">π Linked List</span>
<span class="meta-tag">π’π Floyd's Algorithm</span>
<span class="meta-tag">β±οΈ O(n)</span>
<span class="meta-tag">πΎ O(1)</span>
</div>
<div class="file-ref">
π Python: <code>python/0141_linked_list_cycle/0141_linked_list_cycle.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>π§ How It Works (Layman's Terms)</h4>
<p>Imagine two runners on a circular track - one slow (π’ tortoise) and one fast (π hare):</p>
<ul>
<li><strong>Slow pointer:</strong> Moves 1 step at a time</li>
<li><strong>Fast pointer:</strong> Moves 2 steps at a time</li>
<li><strong>If there's a cycle:</strong> Fast will eventually catch up and meet slow</li>
<li><strong>If no cycle:</strong> Fast will reach the end (null)</li>
<li><strong>Why it works:</strong> In a cycle, fast gains 1 step per iteration, so they must meet!</li>
</ul>
</div>
<div class="visualization-section">
<h3>π¬ Step-by-Step Visualization</h3>
<div class="controls">
<button class="btn btn-primary" id="stepBtn" onclick="step()">Step</button>
<button class="btn btn-success" id="autoBtn" onclick="toggleAuto()">Auto Run</button>
<button class="btn btn-warning" onclick="reset()">Reset</button>
</div>
<div class="info-box secondary" style="margin-bottom: 20px;">
π List: <strong>[3 β 2 β 0 β -4] β (back to node 2)</strong> β Has a cycle!
</div>
<div class="status-message" id="statusMessage">
Click "Step" or "Auto Run" to start visualization
</div>
<div id="linkedListContainer" style="width: 100%; height: 350px; margin-top: 20px;"></div>
<div class="variable-section" style="margin: 20px 0; display: flex; gap: 30px; justify-content: center;">
<div class="variable" style="background: #e3f2fd;">
<span class="var-name">π’ slow</span>
<span class="var-value" id="slowValue">3</span>
<span class="var-desc">moves 1 step</span>
</div>
<div class="variable" style="background: #fce4ec;">
<span class="var-name">π fast</span>
<span class="var-value" id="fastValue">2</span>
<span class="var-desc">moves 2 steps</span>
</div>
<div class="variable">
<span class="var-name">Iteration</span>
<span class="var-value" id="iterValue">0</span>
</div>
</div>
</div>
<div class="code-section">
<h3>π» Python Solution (Floyd's Tortoise and Hare)</h3>
<div class="code-block">
<pre>from typing import List, Optional
"""
LeetCode Linked List Cycle
Problem from LeetCode: https://leetcode.com/problems/linked-list-cycle/
Description:
Given head, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.
Return true if there is a cycle in the linked list. Otherwise, return false.
Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
Example 2:
Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.
Example 3:
Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.
"""
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def has_cycle(self, head: Optional[ListNode]) -> bool:
"""
Determine if a linked list has a cycle using Floyd's Tortoise and Hare algorithm.
Args:
head: Head of the linked list
Returns:
bool: True if the linked list has a cycle, False otherwise
"""
if not head:
return False
slow = head
fast = head.next
while slow and fast:
if not fast or not fast.next:
return False
if fast == slow:
return True
slow = slow.next
fast = fast.next.next
return False
def has_cycle_hashset(self, head: Optional[ListNode]) -> bool:
"""
Determine if a linked list has a cycle using a hash set to track visited nodes.
O(n) time and space complexity.
Args:
head: Head of the linked list
Returns:
bool: True if the linked list has a cycle, False otherwise
"""
visited = set()
current = head
while current:
if current in visited:
return True
visited.add(current)
current = current.next
return False
# Helper function to create a linked list with a cycle
def create_cyclic_linked_list(arr, pos):
if not arr:
return None
head = ListNode(arr[0])
current = head
nodes = [head]
for val in arr[1:]:
current.next = ListNode(val)
current = current.next
nodes.append(current)
# Create cycle if pos is valid
if pos >= 0 and pos < len(nodes):
current.next = nodes[pos]
return head
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
head1 = create_cyclic_linked_list([3, 2, 0, -4], 1)
result1 = solution.has_cycle(head1)
print(f"Example 1: {result1}") # Expected output: True
# Example 2
head2 = create_cyclic_linked_list([1, 2], 0)
result2 = solution.has_cycle(head2)
print(f"Example 2: {result2}") # Expected output: True
# Example 3
head3 = create_cyclic_linked_list([1], -1)
result3 = solution.has_cycle(head3)
print(f"Example 3: {result3}") # Expected output: False
# Compare with hash set approach
print("\nUsing hash set approach:")
head4 = create_cyclic_linked_list([3, 2, 0, -4], 1)
result4 = solution.has_cycle_hashset(head4)
print(f"Example 1: {result4}") # Expected output: True
</pre>
</div>
</div>
</div>
<script>
// Linked list: 3 -> 2 -> 0 -> -4 -> (back to 2)
const nodes = [
{ val: 3, id: 0 },
{ val: 2, id: 1 },
{ val: 0, id: 2 },
{ val: -4, id: 3 }
];
const cycleStart = 1; // Node index where cycle starts (node with value 2)
let slowIdx = 0;
let fastIdx = 1;
let iteration = 0;
let autoInterval = null;
let finished = false;
function getNextIdx(idx) {
if (idx === nodes.length - 1) {
return cycleStart; // Cycle back
}
return idx + 1;
}
function init() {
renderLinkedList();
updateVariables();
}
function renderLinkedList() {
const container = document.getElementById('linkedListContainer');
const width = container.offsetWidth;
const height = container.offsetHeight;
d3.select('#linkedListContainer').selectAll('*').remove();
const svg = d3.select('#linkedListContainer')
.append('svg')
.attr('width', width)
.attr('height', height);
// Position nodes in a shape that shows the cycle
const centerX = width / 2;
const centerY = height / 2;
const nodeRadius = 35;
// Create positions: 3 β 2 β 0 β -4 with -4 looping back to 2
const positions = [
{ x: centerX - 180, y: centerY - 50 }, // Node 0 (val: 3)
{ x: centerX - 60, y: centerY - 50 }, // Node 1 (val: 2) - cycle start
{ x: centerX + 60, y: centerY + 30 }, // Node 2 (val: 0)
{ x: centerX - 60, y: centerY + 110 } // Node 3 (val: -4)
];
// Draw arrows
const arrowHead = svg.append('defs').append('marker')
.attr('id', 'arrowhead')
.attr('viewBox', '0 0 10 10')
.attr('refX', 8)
.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', '#666');
// Regular arrows
for (let i = 0; i < nodes.length - 1; i++) {
const start = positions[i];
const end = positions[i + 1];
const angle = Math.atan2(end.y - start.y, end.x - start.x);
svg.append('line')
.attr('x1', start.x + nodeRadius * Math.cos(angle))
.attr('y1', start.y + nodeRadius * Math.sin(angle))
.attr('x2', end.x - nodeRadius * Math.cos(angle))
.attr('y2', end.y - nodeRadius * Math.sin(angle))
.attr('stroke', '#666')
.attr('stroke-width', 2)
.attr('marker-end', 'url(#arrowhead)');
}
// Cycle arrow (from -4 back to 2)
const lastPos = positions[3];
const cyclePos = positions[1];
// Draw curved arrow for cycle
svg.append('path')
.attr('d', `M ${lastPos.x - 20} ${lastPos.y - 20}
Q ${lastPos.x - 100} ${lastPos.y - 80}
${cyclePos.x - 20} ${cyclePos.y + 20}`)
.attr('fill', 'none')
.attr('stroke', '#e91e63')
.attr('stroke-width', 2)
.attr('stroke-dasharray', '5,5')
.attr('marker-end', 'url(#arrowhead)');
// Cycle label
svg.append('text')
.attr('x', lastPos.x - 100)
.attr('y', lastPos.y - 60)
.attr('fill', '#e91e63')
.attr('font-size', '12px')
.text('cycle!');
// Draw nodes
nodes.forEach((node, i) => {
const pos = positions[i];
const g = svg.append('g')
.attr('transform', `translate(${pos.x}, ${pos.y})`);
// Node circle
let fillColor = '#fff';
let strokeColor = '#667eea';
let strokeWidth = 3;
if (slowIdx === i && fastIdx === i) {
fillColor = '#ab47bc'; // Purple when both are here
strokeWidth = 5;
} else if (slowIdx === i) {
fillColor = '#2196f3'; // Blue for slow
strokeWidth = 5;
} else if (fastIdx === i) {
fillColor = '#e91e63'; // Pink for fast
strokeWidth = 5;
}
if (i === cycleStart) {
strokeColor = '#e91e63';
}
g.append('circle')
.attr('r', nodeRadius)
.attr('fill', fillColor)
.attr('stroke', strokeColor)
.attr('stroke-width', strokeWidth);
// Node value
g.append('text')
.attr('text-anchor', 'middle')
.attr('dy', 5)
.attr('font-size', '18px')
.attr('font-weight', 'bold')
.attr('fill', (slowIdx === i || fastIdx === i) ? '#fff' : '#333')
.text(node.val);
// Node index
g.append('text')
.attr('text-anchor', 'middle')
.attr('dy', -45)
.attr('font-size', '12px')
.attr('fill', '#666')
.text(`index: ${i}`);
// Pointer labels
if (slowIdx === i && fastIdx === i) {
g.append('text')
.attr('text-anchor', 'middle')
.attr('dy', 55)
.attr('font-size', '14px')
.attr('fill', '#ab47bc')
.text('π’π MEET!');
} else {
if (slowIdx === i) {
g.append('text')
.attr('text-anchor', 'middle')
.attr('dy', 55)
.attr('font-size', '14px')
.attr('fill', '#2196f3')
.text('π’ slow');
}
if (fastIdx === i) {
g.append('text')
.attr('text-anchor', 'middle')
.attr('dy', fastIdx === slowIdx ? 75 : 55)
.attr('font-size', '14px')
.attr('fill', '#e91e63')
.text('π fast');
}
}
});
// Legend
svg.append('circle').attr('cx', 30).attr('cy', 20).attr('r', 8).attr('fill', '#2196f3');
svg.append('text').attr('x', 45).attr('y', 24).text('slow (π’)').attr('font-size', '12px');
svg.append('circle').attr('cx', 30).attr('cy', 45).attr('r', 8).attr('fill', '#e91e63');
svg.append('text').attr('x', 45).attr('y', 49).text('fast (π)').attr('font-size', '12px');
}
function updateVariables() {
document.getElementById('slowValue').textContent = nodes[slowIdx].val;
document.getElementById('fastValue').textContent = nodes[fastIdx].val;
document.getElementById('iterValue').textContent = iteration;
}
function step() {
if (finished) return;
iteration++;
// Check if they meet
if (slowIdx === fastIdx) {
finished = true;
document.getElementById('statusMessage').className = 'status-message success';
document.getElementById('statusMessage').textContent =
`β
CYCLE DETECTED! Slow and fast pointers meet at node ${nodes[slowIdx].val}`;
document.getElementById('stepBtn').disabled = true;
stopAuto();
renderLinkedList();
updateVariables();
return;
}
// Move slow by 1
const oldSlow = slowIdx;
slowIdx = getNextIdx(slowIdx);
// Move fast by 2
const oldFast = fastIdx;
fastIdx = getNextIdx(fastIdx);
fastIdx = getNextIdx(fastIdx);
document.getElementById('statusMessage').textContent =
`Iteration ${iteration}: slow ${nodes[oldSlow].val} β ${nodes[slowIdx].val}, fast ${nodes[oldFast].val} β ${nodes[fastIdx].val}`;
renderLinkedList();
updateVariables();
// Check again after move
if (slowIdx === fastIdx) {
finished = true;
document.getElementById('statusMessage').className = 'status-message success';
document.getElementById('statusMessage').textContent =
`β
CYCLE DETECTED! Slow and fast pointers meet at node ${nodes[slowIdx].val}`;
document.getElementById('stepBtn').disabled = true;
stopAuto();
}
}
function toggleAuto() {
if (autoInterval) {
stopAuto();
} else {
document.getElementById('autoBtn').textContent = 'Pause';
autoInterval = setInterval(() => {
if (finished) {
stopAuto();
} else {
step();
}
}, 1000);
}
}
function stopAuto() {
if (autoInterval) {
clearInterval(autoInterval);
autoInterval = null;
}
document.getElementById('autoBtn').textContent = 'Auto Run';
}
function reset() {
stopAuto();
slowIdx = 0;
fastIdx = 1;
iteration = 0;
finished = false;
document.getElementById('stepBtn').disabled = false;
document.getElementById('statusMessage').className = 'status-message';
document.getElementById('statusMessage').textContent = 'Click "Step" or "Auto Run" to start visualization';
init();
}
init();
</script>
</body>
</html>