-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0019_remove_nth_node.html
More file actions
552 lines (472 loc) · 20.2 KB
/
0019_remove_nth_node.html
File metadata and controls
552 lines (472 loc) · 20.2 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Remove Nth Node From End - Algorithm Visualization</title>
<link rel="stylesheet" href="styles.css">
<script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
</div>
<div class="container">
<div class="problem-info">
<h1><span class="problem-number">#0019</span> Remove Nth Node From End of List</h1>
<p>
Given the head of a linked list, remove the <strong>nth node from the end</strong> of the list
and return its head. Uses a two-pointer technique with a gap of n+1 nodes.
</p>
<p><strong>Example:</strong> head = [1,2,3,4,5], n = 2 → Output: [1,2,3,5]</p>
<p><strong>Time Complexity:</strong> O(n) - single pass</p>
<p><strong>Space Complexity:</strong> O(1)</p>
<div class="problem-meta">
<span class="meta-tag">🔗 Linked List</span>
<span class="meta-tag">⏱️ O(n)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0019_remove_nth_node_from_end_of_list/0019_remove_nth_node_from_end_of_list.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>A linked list is like a <strong>chain of train cars</strong>:</p>
<ul>
<li><strong>Each node:</strong> Contains data and points to next node</li>
<li><strong>Traversal:</strong> Follow the chain one node at a time</li>
<li><strong>Modification:</strong> Redirect links to rearrange</li>
<li><strong>Two pointers:</strong> Often use slow/fast pointers</li>
</ul>
</div>
<div class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="controls">
<button id="stepBtn" class="btn">Step</button>
<button id="autoBtn" class="btn">Auto Run</button>
<button id="resetBtn" class="btn btn-secondary">Reset</button>
<div class="speed-control">
<label for="speedSlider">Speed:</label>
<input type="range" id="speedSlider" min="1" max="10" value="5">
</div>
</div>
<svg id="visualization" width="900" height="400"></svg>
<div class="variables-display">
<div id="varDisplay"></div>
</div>
<div class="status-message" id="statusMessage">Press "Step" or "Auto Run" to begin</div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List, Optional
"""
LeetCode Remove Nth Node From End of List
Problem from LeetCode: https://leetcode.com/problems/remove-nth-node-from-end-of-list/
Description:
Given the head of a linked list, remove the nth node from the end of the list and return its head.
Example 1:
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
Explanation: After removing the second node from the end, the linked list becomes [1,2,3,5].
Example 2:
Input: head = [1], n = 1
Output: []
Explanation: After removing the first node from the end, the linked list becomes empty.
Example 3:
Input: head = [1,2], n = 1
Output: [1]
Explanation: After removing the first node from the end, the linked list becomes [1].
"""
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def remove_nth_from_end(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
"""
Remove the nth node from the end of the linked list.
Uses a two-pointer approach to find the node to remove in a single pass.
Args:
head: Head of the linked list
n: Position from the end to remove (1-indexed)
Returns:
ListNode: Head of the modified linked list
"""
# Create a dummy node to handle edge cases
dummy = ListNode(0)
dummy.next = head
# Initialize two pointers
first = dummy
second = dummy
# Advance first pointer by n+1 steps
for i in range(n + 1):
if not first:
return None # Invalid n (too large)
first = first.next
# Move both pointers until first reaches the end
while first:
first = first.next
second = second.next
# Remove the nth node from the end
second.next = second.next.next
return dummy.next
def remove_nth_from_end_two_pass(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
"""
Remove the nth node from the end using a two-pass approach.
First pass counts the length, second pass finds the node to remove.
Args:
head: Head of the linked list
n: Position from the end to remove (1-indexed)
Returns:
ListNode: Head of the modified linked list
"""
# Create a dummy node
dummy = ListNode(0)
dummy.next = head
# First pass: count the length of the list
length = 0
current = head
while current:
length += 1
current = current.next
# Second pass: find the node before the one to remove
position = length - n
current = dummy
for i in range(position):
current = current.next
# Remove the nth node from the end
current.next = current.next.next
return dummy.next
# Helper function to create a linked list from an array
def create_linked_list(arr):
if not arr:
return None
head = ListNode(arr[0])
current = head
for val in arr[1:]:
current.next = ListNode(val)
current = current.next
return head
# Helper function to convert a linked list to an array
def linked_list_to_array(head):
result = []
current = head
while current:
result.append(current.val)
current = current.next
return result
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
head1 = create_linked_list([1, 2, 3, 4, 5])
n1 = 2
result1 = solution.remove_nth_from_end(head1, n1)
print(f"Example 1: n={n1}, Result={linked_list_to_array(result1)}") # Expected: [1,2,3,5]
# Example 2
head2 = create_linked_list([1])
n2 = 1
result2 = solution.remove_nth_from_end(head2, n2)
print(f"Example 2: n={n2}, Result={linked_list_to_array(result2)}") # Expected: []
# Example 3
head3 = create_linked_list([1, 2])
n3 = 1
result3 = solution.remove_nth_from_end(head3, n3)
print(f"Example 3: n={n3}, Result={linked_list_to_array(result3)}") # Expected: [1]
# Compare with two-pass approach
head4 = create_linked_list([1, 2, 3, 4, 5])
result4 = solution.remove_nth_from_end_two_pass(head4, 2)
print(f"Two-pass approach: Result={linked_list_to_array(result4)}") # Expected: [1,2,3,5]
</pre>
</div>
</div>
</div>
<script>
// Data
const values = [1, 2, 3, 4, 5];
const n = 2; // Remove 2nd from end (node with value 4)
// State
let step = 0;
let autoRunning = false;
let autoInterval = null;
// Generate steps
const steps = [];
function generateSteps() {
steps.length = 0;
const nodes = ['dummy', ...values.map(String)];
steps.push({
type: 'init',
nodes: [...nodes],
first: 0,
second: 0,
removed: -1,
message: 'Initialize: Create dummy node, both pointers at dummy'
});
// Advance first by n+1 steps
for (let i = 1; i <= n + 1; i++) {
steps.push({
type: 'advance_first',
nodes: [...nodes],
first: i,
second: 0,
removed: -1,
message: `Advance first pointer: step ${i} of ${n + 1}`
});
}
// Move both until first reaches end
let firstPos = n + 1;
let secondPos = 0;
while (firstPos < nodes.length) {
firstPos++;
secondPos++;
steps.push({
type: 'move_both',
nodes: [...nodes],
first: firstPos,
second: secondPos,
removed: -1,
message: `Move both pointers. Gap maintained at ${n + 1}`
});
}
// Show what we're about to remove
const toRemove = secondPos + 1;
steps.push({
type: 'identify',
nodes: [...nodes],
first: firstPos,
second: secondPos,
toRemove: toRemove,
removed: -1,
message: `First reached end. Second.next (node ${toRemove}) is the ${n}th from end`
});
// Remove the node
const newNodes = nodes.filter((_, i) => i !== toRemove);
steps.push({
type: 'remove',
nodes: newNodes,
originalNodes: [...nodes],
first: firstPos,
second: secondPos,
removed: toRemove,
message: `Remove node with value ${nodes[toRemove]}. Link second.next to second.next.next`
});
steps.push({
type: 'done',
nodes: newNodes,
first: -1,
second: -1,
removed: -1,
message: `Done! Result: [${newNodes.slice(1).join(', ')}]`
});
}
// SVG setup
const svg = d3.select("#visualization");
const width = 900;
const height = 400;
function draw(currentStep) {
svg.selectAll("*").remove();
const data = currentStep || steps[0];
const nodeWidth = 60;
const nodeHeight = 40;
const gap = 90;
const startX = 80;
const startY = 150;
// Arrow marker
svg.append("defs").append("marker")
.attr("id", "arrow")
.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", "#667eea");
// Draw original nodes with removal effect
if (data.type === 'remove' && data.originalNodes) {
data.originalNodes.forEach((val, i) => {
const x = startX + i * gap;
const isRemoved = i === data.removed;
if (isRemoved) {
const group = svg.append("g")
.attr("transform", `translate(${x}, ${startY})`);
group.append("rect")
.attr("width", nodeWidth)
.attr("height", nodeHeight)
.attr("rx", 8)
.attr("fill", "#fee2e2")
.attr("stroke", "#ef4444")
.attr("stroke-width", 2)
.attr("stroke-dasharray", "5,5")
.attr("opacity", 0.5);
group.append("text")
.attr("x", nodeWidth / 2)
.attr("y", nodeHeight / 2 + 5)
.attr("text-anchor", "middle")
.attr("fill", "#ef4444")
.attr("font-weight", "bold")
.attr("text-decoration", "line-through")
.text(val);
// Draw bypass arrow
const prevX = startX + (i - 1) * gap + nodeWidth;
const nextX = startX + (i + 1) * gap;
svg.append("path")
.attr("d", `M ${prevX} ${startY + nodeHeight / 2} Q ${x + nodeWidth / 2} ${startY - 40} ${nextX} ${startY + nodeHeight / 2}`)
.attr("fill", "none")
.attr("stroke", "#4ade80")
.attr("stroke-width", 3)
.attr("marker-end", "url(#arrow)");
}
});
}
// Draw nodes
const displayNodes = data.nodes || ['dummy', '1', '2', '3', '4', '5'];
displayNodes.forEach((val, i) => {
const x = startX + i * gap;
const group = svg.append("g")
.attr("transform", `translate(${x}, ${startY})`);
let fillColor = val === 'dummy' ? '#9ca3af' : '#667eea';
let strokeColor = 'none';
let strokeWidth = 0;
if (data.toRemove === i) {
fillColor = '#ef4444';
strokeColor = '#991b1b';
strokeWidth = 3;
}
group.append("rect")
.attr("width", nodeWidth)
.attr("height", nodeHeight)
.attr("rx", 8)
.attr("fill", fillColor)
.attr("stroke", strokeColor)
.attr("stroke-width", strokeWidth);
group.append("text")
.attr("x", nodeWidth / 2)
.attr("y", nodeHeight / 2 + 5)
.attr("text-anchor", "middle")
.attr("fill", "white")
.attr("font-weight", "bold")
.attr("font-size", val === 'dummy' ? "12px" : "16px")
.text(val);
// Draw arrows between nodes
if (i < displayNodes.length - 1) {
svg.append("line")
.attr("x1", x + nodeWidth)
.attr("y1", startY + nodeHeight / 2)
.attr("x2", x + gap - 5)
.attr("y2", startY + nodeHeight / 2)
.attr("stroke", "#667eea")
.attr("stroke-width", 2)
.attr("marker-end", "url(#arrow)");
}
});
// Draw first pointer
if (data.first >= 0 && data.first <= displayNodes.length) {
const firstX = startX + data.first * gap + nodeWidth / 2;
const firstY = startY - 60;
svg.append("polygon")
.attr("points", `${firstX},${firstY + 30} ${firstX - 10},${firstY} ${firstX + 10},${firstY}`)
.attr("fill", "#ef4444");
svg.append("text")
.attr("x", firstX)
.attr("y", firstY - 10)
.attr("text-anchor", "middle")
.attr("fill", "#ef4444")
.attr("font-weight", "bold")
.text("first");
}
// Draw second pointer
if (data.second >= 0 && data.second < displayNodes.length) {
const secondX = startX + data.second * gap + nodeWidth / 2;
const secondY = startY + nodeHeight + 60;
svg.append("polygon")
.attr("points", `${secondX},${secondY - 30} ${secondX - 10},${secondY} ${secondX + 10},${secondY}`)
.attr("fill", "#4ade80");
svg.append("text")
.attr("x", secondX)
.attr("y", secondY + 20)
.attr("text-anchor", "middle")
.attr("fill", "#16a34a")
.attr("font-weight", "bold")
.text("second");
}
// Draw gap indicator
if (data.first > 0 && data.second >= 0 && data.first <= displayNodes.length && data.type !== 'done') {
const gapValue = data.first - data.second;
svg.append("text")
.attr("x", 750)
.attr("y", 50)
.attr("text-anchor", "middle")
.attr("class", "label")
.text(`Gap: ${gapValue} (n+1 = ${n + 1})`);
}
// Draw n value
svg.append("text")
.attr("x", 750)
.attr("y", 90)
.attr("text-anchor", "middle")
.attr("fill", "#6b7280")
.text(`n = ${n} (remove ${n}th from end)`);
// Legend
const legendY = 320;
svg.append("rect").attr("x", 50).attr("y", legendY).attr("width", 20).attr("height", 20).attr("fill", "#ef4444");
svg.append("text").attr("x", 80).attr("y", legendY + 15).attr("fill", "#4b5563").text("First pointer");
svg.append("rect").attr("x", 200).attr("y", legendY).attr("width", 20).attr("height", 20).attr("fill", "#4ade80");
svg.append("text").attr("x", 230).attr("y", legendY + 15).attr("fill", "#4b5563").text("Second pointer");
// Update status
document.getElementById("statusMessage").textContent = data.message;
// Update variables
document.getElementById("varDisplay").innerHTML = `
<span class="var-item">First: ${data.first >= 0 ? data.first : 'N/A'}</span>
<span class="var-item">Second: ${data.second >= 0 ? data.second : 'N/A'}</span>
<span class="var-item">n: ${n}</span>
<span class="var-item">Gap: ${data.first > 0 && data.second >= 0 ? data.first - data.second : 'N/A'}</span>
`;
}
function doStep() {
if (step >= steps.length) {
stopAuto();
return;
}
draw(steps[step]);
step++;
}
function stopAuto() {
autoRunning = false;
if (autoInterval) {
clearInterval(autoInterval);
autoInterval = null;
}
document.getElementById("autoBtn").textContent = "Auto Run";
}
function toggleAuto() {
if (autoRunning) {
stopAuto();
} else {
autoRunning = true;
document.getElementById("autoBtn").textContent = "Pause";
const speed = 11 - document.getElementById("speedSlider").value;
autoInterval = setInterval(() => {
if (step >= steps.length) {
stopAuto();
return;
}
doStep();
}, speed * 200);
}
}
function reset() {
stopAuto();
step = 0;
draw(steps[0]);
}
// Initialize
generateSteps();
draw(steps[0]);
// Event listeners
document.getElementById("stepBtn").addEventListener("click", doStep);
document.getElementById("autoBtn").addEventListener("click", toggleAuto);
document.getElementById("resetBtn").addEventListener("click", reset);
</script>
</body>
</html>