-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0876_middle_of_the_linked_list.html
More file actions
407 lines (344 loc) · 14.3 KB
/
0876_middle_of_the_linked_list.html
File metadata and controls
407 lines (344 loc) · 14.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LC 876: Middle of the Linked List - 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">#876</span> Middle of the Linked List</h1>
<p>Given the head of a singly linked list, return the middle node. If two middle nodes, return the second one.</p>
<div class="problem-meta">
<span class="meta-tag">🔗 Linked List</span>
<span class="meta-tag">👉👉 Two Pointers</span>
<span class="meta-tag">⏱️ O(n)</span>
<span class="meta-tag">💾 O(1)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0876_middle_of_the_linked_list/0876_middle_of_the_linked_list.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>Imagine two runners on a track. One runs twice as fast:</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>When fast reaches end:</strong> Slow is at the middle!</li>
<li><strong>Why?</strong> Fast travels 2x distance, so slow is at halfway</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>
<select id="listSize" style="padding: 8px; border-radius: 5px; margin-left: 10px;">
<option value="5">5 nodes</option>
<option value="6" selected>6 nodes</option>
<option value="7">7 nodes</option>
</select>
</div>
<div class="status-message" id="statusMessage">
Click "Step" to find the middle node using slow/fast pointers
</div>
<div class="variable-display">
<div class="variable-box">
<div class="variable-name">🐢 Slow</div>
<div class="variable-value" id="slowVal" style="color: #4caf50;">1</div>
</div>
<div class="variable-box">
<div class="variable-name">🐇 Fast</div>
<div class="variable-value" id="fastVal" style="color: #ff5722;">1</div>
</div>
<div class="variable-box">
<div class="variable-name">Middle</div>
<div class="variable-value" id="middleVal">?</div>
</div>
</div>
<div class="array-section">
<div class="array-label">🔗 Linked List:</div>
<div id="listContainer" class="linked-list-container"></div>
</div>
<div style="margin-top: 20px; text-align: center;">
<svg id="pointerViz" width="100%" height="80"></svg>
</div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import Optional
"""
LeetCode Middle of the Linked List
Problem from LeetCode: https://leetcode.com/problems/middle-of-the-linked-list/
Description:
Given the head of a singly linked list, return the middle node of the linked list.
If there are two middle nodes, return the second middle node.
Example 1:
Input: head = [1,2,3,4,5]
Output: [3,4,5]
Explanation: The middle node of the list is node 3.
Example 2:
Input: head = [1,2,3,4,5,6]
Output: [4,5,6]
Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one.
"""
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def middle_node(self, head: Optional[ListNode]) ->Optional[ListNode]:
"""
Return the middle node of a linked list.
If there are two middle nodes, return the second middle node.
Args:
head: Head of the linked list
Returns:
ListNode: The middle node of the linked list
"""
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
def middleNode_array(self, head: Optional[ListNode]) ->Optional[ListNode]:
"""
Find the middle node using an array.
Args:
head: Head of the linked list
Returns:
ListNode: The middle node of the linked list
"""
nodes = []
current = head
while current:
nodes.append(current)
current = current.next
return nodes[len(nodes) // 2]
def middleNode_count(self, head: Optional[ListNode]) ->Optional[ListNode]:
"""
Find the middle node by counting nodes.
Args:
head: Head of the linked list
Returns:
ListNode: The middle node of the linked list
"""
count = 0
current = head
while current:
count += 1
current = current.next
middle = count // 2
current = head
for _ in range(middle):
current = current.next
return current
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1: Create the linked list [1,2,3,4,5]
head1 = ListNode(1)
head1.next = ListNode(2)
head1.next.next = ListNode(3)
head1.next.next.next = ListNode(4)
head1.next.next.next.next = ListNode(5)
result1 = solution.middle_node(head1)
# Print the result
print("Example 1 result:")
output1 = []
while result1:
output1.append(result1.val)
result1 = result1.next
print(output1) # Expected output: [3,4,5]
# Example 2: Create the linked list [1,2,3,4,5,6]
head2 = ListNode(1)
head2.next = ListNode(2)
head2.next.next = ListNode(3)
head2.next.next.next = ListNode(4)
head2.next.next.next.next = ListNode(5)
head2.next.next.next.next.next = ListNode(6)
result2 = solution.middle_node(head2)
# Print the result
print("Example 2 result:")
output2 = []
while result2:
output2.append(result2.val)
result2 = result2.next
print(output2) # Expected output: [4,5,6]
</pre>
</div>
</div>
</div>
<script>
let values = [1, 2, 3, 4, 5, 6];
let slowIdx = 0;
let fastIdx = 0;
let done = false;
let autoInterval = null;
function init() {
const size = parseInt(document.getElementById('listSize').value);
values = Array.from({length: size}, (_, i) => i + 1);
renderList();
}
function renderList() {
const container = document.getElementById('listContainer');
container.innerHTML = '';
for (let i = 0; i < values.length; i++) {
const nodeDiv = document.createElement('div');
nodeDiv.className = 'list-node';
const box = document.createElement('div');
box.className = 'node-box';
box.textContent = values[i];
box.id = `node-${i}`;
if (done && i === slowIdx) {
box.style.background = '#4caf50';
box.style.transform = 'scale(1.2)';
} else if (i === slowIdx && i === fastIdx) {
box.style.background = 'linear-gradient(135deg, #4caf50 50%, #ff5722 50%)';
} else if (i === slowIdx) {
box.style.background = '#4caf50';
} else if (i === fastIdx) {
box.style.background = '#ff5722';
}
nodeDiv.appendChild(box);
if (i < values.length - 1) {
const arrow = document.createElement('span');
arrow.className = 'node-arrow';
arrow.textContent = '→';
nodeDiv.appendChild(arrow);
}
container.appendChild(nodeDiv);
}
const nullSpan = document.createElement('span');
nullSpan.className = 'null-node';
nullSpan.textContent = '→ null';
container.appendChild(nullSpan);
renderPointers();
}
function renderPointers() {
const svg = d3.select("#pointerViz");
svg.selectAll("*").remove();
const container = document.getElementById('listContainer');
const width = container.scrollWidth;
svg.attr("viewBox", `0 0 ${width} 80`);
const nodeWidth = 60;
const gap = 8;
const offset = 30;
// Slow pointer (turtle)
const slowX = offset + slowIdx * (nodeWidth + gap + 20);
svg.append("text")
.attr("x", slowX)
.attr("y", 30)
.attr("text-anchor", "middle")
.attr("font-size", "24px")
.text("🐢");
svg.append("text")
.attr("x", slowX)
.attr("y", 55)
.attr("text-anchor", "middle")
.attr("fill", "#4caf50")
.attr("font-size", "12px")
.attr("font-weight", "bold")
.text("slow");
// Fast pointer (rabbit) - only if not past end
if (fastIdx < values.length) {
const fastX = offset + fastIdx * (nodeWidth + gap + 20);
svg.append("text")
.attr("x", fastX)
.attr("y", 30)
.attr("text-anchor", "middle")
.attr("font-size", "24px")
.text("🐇");
svg.append("text")
.attr("x", fastX)
.attr("y", 55)
.attr("text-anchor", "middle")
.attr("fill", "#ff5722")
.attr("font-size", "12px")
.attr("font-weight", "bold")
.text("fast");
}
}
function step() {
if (done) return;
// Check if fast can move
if (fastIdx >= values.length - 1 || fastIdx + 1 >= values.length) {
done = true;
document.getElementById('middleVal').textContent = values[slowIdx];
document.getElementById('statusMessage').className = 'status-message success';
document.getElementById('statusMessage').textContent =
`✅ Found middle! Node with value ${values[slowIdx]} at index ${slowIdx}`;
document.getElementById('stepBtn').disabled = true;
stopAuto();
renderList();
return;
}
// Move pointers
slowIdx += 1;
fastIdx += 2;
document.getElementById('slowVal').textContent = values[slowIdx];
document.getElementById('fastVal').textContent =
fastIdx < values.length ? values[fastIdx] : 'null';
document.getElementById('statusMessage').textContent =
`slow moves to ${values[slowIdx]}, fast moves to ${fastIdx < values.length ? values[fastIdx] : 'null'}`;
renderList();
// Check if we should stop
if (fastIdx >= values.length - 1) {
done = true;
document.getElementById('middleVal').textContent = values[slowIdx];
document.getElementById('statusMessage').className = 'status-message success';
document.getElementById('statusMessage').textContent =
`✅ Fast reached end! Middle is ${values[slowIdx]}`;
document.getElementById('stepBtn').disabled = true;
stopAuto();
}
}
function toggleAuto() {
if (autoInterval) {
stopAuto();
} else {
document.getElementById('autoBtn').textContent = 'Pause';
autoInterval = setInterval(() => {
if (done) {
stopAuto();
} else {
step();
}
}, 800);
}
}
function stopAuto() {
if (autoInterval) {
clearInterval(autoInterval);
autoInterval = null;
}
document.getElementById('autoBtn').textContent = 'Auto Run';
}
function reset() {
stopAuto();
slowIdx = 0;
fastIdx = 0;
done = false;
document.getElementById('stepBtn').disabled = false;
document.getElementById('statusMessage').className = 'status-message';
document.getElementById('statusMessage').textContent =
'Click "Step" to find the middle node using slow/fast pointers';
document.getElementById('middleVal').textContent = '?';
init();
document.getElementById('slowVal').textContent = values[0];
document.getElementById('fastVal').textContent = values[0];
}
document.getElementById('listSize').addEventListener('change', reset);
init();
document.getElementById('slowVal').textContent = values[0];
document.getElementById('fastVal').textContent = values[0];
</script>
</body>
</html>