-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0025_reverse_nodes_in_k_group.html
More file actions
629 lines (539 loc) · 21.9 KB
/
0025_reverse_nodes_in_k_group.html
File metadata and controls
629 lines (539 loc) · 21.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
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>025 - Reverse Nodes in k-Group</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">#025</span> Reverse Nodes in k-Group</h1>
<p>
Reverse nodes in k-group in a linked list. If remaining nodes < k, keep them as-is.
Uses iterative reversal of each group and reconnects them.
</p>
<div class="problem-meta">
<span class="meta-tag">🔗 Linked List</span>
<span class="meta-tag">🗂️ Hash Map</span>
<span class="meta-tag">⏱️ O(n)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0025_reverse_nodes_in_k_group/0025_reverse_nodes_in_k_group.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>
<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 reverse nodes in groups of k=2</div>
<svg id="visualization"></svg>
</section>
<section class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import Optional
"""
LeetCode Reverse Nodes in k-Group
Problem from LeetCode: https://leetcode.com/problems/reverse-nodes-in-k-group/
Description:
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.
You may not alter the values in the list's nodes, only nodes themselves may be changed.
Example 1:
Input: head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]
Example 2:
Input: head = [1,2,3,4,5], k = 3
Output: [3,2,1,4,5]
Example 3:
Input: head = [1,2,3,4,5], k = 1
Output: [1,2,3,4,5]
Example 4:
Input: head = [1], k = 1
Output: [1]
"""
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverse_k_group(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
"""
Reverse nodes in k-group in a linked list.
Args:
head: Head of the linked list
k: Number of nodes to reverse at a time
Returns:
ListNode: Head of the modified linked list with k-groups reversed
"""
# Check if we need to reverse (base case for recursion)
count = 0
curr = head
while curr and count < k:
curr = curr.next
count += 1
# If we don't have k nodes, return the head without reversing
if count < k:
return head
# Reverse k nodes
prev = None
curr = head
for _ in range(k):
next_temp = curr.next
curr.next = prev
prev = curr
curr = next_temp
# Connect the reversed group with the rest of the list
# head is now the last node of the reversed group
head.next = self.reverse_k_group(curr, k)
# prev is now the first node of the reversed group (new head)
return prev
def reverse_k_group_iterative(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
"""
Iterative approach to reverse nodes in k-group.
Args:
head: Head of the linked list
k: Number of nodes to reverse at a time
Returns:
ListNode: Head of the modified linked list with k-groups reversed
"""
dummy = ListNode(0, head)
group_prev = dummy
while True:
# Check if we have k nodes left
kth = self._get_kth(group_prev, k)
if not kth:
break
group_next = kth.next
# Reverse the group
prev, curr = group_next, group_prev.next
for _ in range(k):
next_temp = curr.next
curr.next = prev
prev = curr
curr = next_temp
# Connect with the rest of the list
temp = group_prev.next
group_prev.next = kth
group_prev = temp
return dummy.next
def _get_kth(self, curr: ListNode, k: int) -> Optional[ListNode]:
"""Helper function to get the kth node from current."""
while curr and k > 0:
curr = curr.next
k -= 1
return curr
# 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])
k1 = 2
result1 = solution.reverse_k_group(head1, k1)
print(f"Example 1: k={k1}, Result={linked_list_to_array(result1)}") # Expected: [2,1,4,3,5]
# Example 2
head2 = create_linked_list([1, 2, 3, 4, 5])
k2 = 3
result2 = solution.reverse_k_group(head2, k2)
print(f"Example 2: k={k2}, Result={linked_list_to_array(result2)}") # Expected: [3,2,1,4,5]
# Example 3
head3 = create_linked_list([1, 2, 3, 4, 5])
k3 = 1
result3 = solution.reverse_k_group(head3, k3)
print(f"Example 3: k={k3}, Result={linked_list_to_array(result3)}") # Expected: [1,2,3,4,5]
# Example 4
head4 = create_linked_list([1])
k4 = 1
result4 = solution.reverse_k_group(head4, k4)
print(f"Example 4: k={k4}, Result={linked_list_to_array(result4)}") # Expected: [1]
# Test iterative approach
head5 = create_linked_list([1, 2, 3, 4, 5, 6, 7, 8])
k5 = 3
result5 = solution.reverse_k_group_iterative(head5, k5)
print(f"Iterative approach: k={k5}, Result={linked_list_to_array(result5)}") # Expected: [3,2,1,6,5,4,7,8]
</pre>
</div>
</section>
</div>
<script>
const width = 900;
const height = 550;
const svg = d3.select("#visualization")
.attr("width", width)
.attr("height", height);
const originalList = [1, 2, 3, 4, 5];
const k = 2;
let nodes = [];
let groupStart = 0;
let phase = 0; // 0: init, 1: finding kth, 2: reversing, 3: reconnecting, 4: done
let reverseIdx = 0;
let animationTimer = null;
let currentGroup = [];
let reversedGroups = [];
function reset() {
nodes = originalList.map((val, idx) => ({
val,
originalIdx: idx,
currentIdx: idx,
inGroup: false,
reversed: false
}));
groupStart = 0;
phase = 0;
reverseIdx = 0;
currentGroup = [];
reversedGroups = [];
if (animationTimer) clearInterval(animationTimer);
document.getElementById("status").textContent = `Reversing in groups of k=${k}`;
render();
}
function render() {
svg.selectAll("*").remove();
const nodeWidth = 50;
const spacing = 80;
const startX = 80;
const startY = 100;
// Title
svg.append("text")
.attr("x", 30)
.attr("y", 40)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text(`List: [${originalList.join(' → ')}], k = ${k}`);
// Draw current state
svg.append("text")
.attr("x", 30)
.attr("y", startY - 25)
.attr("font-size", "13px")
.attr("fill", "#64748b")
.text("Current State:");
// Draw nodes in their current order
const sortedNodes = [...nodes].sort((a, b) => a.currentIdx - b.currentIdx);
sortedNodes.forEach((node, displayIdx) => {
const x = startX + displayIdx * spacing;
const y = startY;
const isInCurrentGroup = currentGroup.includes(node.originalIdx);
const isReversed = node.reversed;
svg.append("rect")
.attr("x", x)
.attr("y", y)
.attr("width", nodeWidth)
.attr("height", 40)
.attr("rx", 8)
.attr("fill", () => {
if (isInCurrentGroup) return "#fef3c7";
if (isReversed) return "#d1fae5";
return "#dbeafe";
})
.attr("stroke", () => {
if (isInCurrentGroup) return "#f59e0b";
if (isReversed) return "#10b981";
return "#3b82f6";
})
.attr("stroke-width", isInCurrentGroup ? 3 : 2);
svg.append("text")
.attr("x", x + nodeWidth / 2)
.attr("y", y + 27)
.attr("text-anchor", "middle")
.attr("font-size", "18px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text(node.val);
// Draw arrows between nodes
if (displayIdx < sortedNodes.length - 1) {
svg.append("line")
.attr("x1", x + nodeWidth)
.attr("y1", y + 20)
.attr("x2", x + spacing - 5)
.attr("y2", y + 20)
.attr("stroke", "#94a3b8")
.attr("stroke-width", 2)
.attr("marker-end", "url(#arrow)");
}
});
// 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", "#94a3b8");
// Draw group visualization
drawGroups();
// Draw algorithm steps
drawAlgorithmSteps();
}
function drawGroups() {
const startX = 80;
const startY = 200;
svg.append("text")
.attr("x", 30)
.attr("y", startY)
.attr("font-size", "13px")
.attr("fill", "#64748b")
.text("Groups:");
// Show groups
const numFullGroups = Math.floor(originalList.length / k);
const remaining = originalList.length % k;
for (let g = 0; g < numFullGroups; g++) {
const x = startX + g * 200;
const groupVals = [];
// Determine if this group has been processed
const isProcessed = g < reversedGroups.length;
const isCurrent = g * k === groupStart && phase > 0 && phase < 4;
for (let i = 0; i < k; i++) {
const originalIdx = g * k + i;
if (isProcessed) {
// Show reversed order
groupVals.push(originalList[g * k + k - 1 - i]);
} else {
groupVals.push(originalList[originalIdx]);
}
}
svg.append("rect")
.attr("x", x)
.attr("y", startY + 15)
.attr("width", 150)
.attr("height", 40)
.attr("rx", 8)
.attr("fill", () => {
if (isCurrent) return "#fef3c7";
if (isProcessed) return "#d1fae5";
return "#f8fafc";
})
.attr("stroke", () => {
if (isCurrent) return "#f59e0b";
if (isProcessed) return "#10b981";
return "#94a3b8";
})
.attr("stroke-width", isCurrent ? 3 : 2);
svg.append("text")
.attr("x", x + 75)
.attr("y", startY + 42)
.attr("text-anchor", "middle")
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text(`[${groupVals.join(' → ')}]`);
svg.append("text")
.attr("x", x + 75)
.attr("y", startY + 72)
.attr("text-anchor", "middle")
.attr("font-size", "11px")
.attr("fill", "#64748b")
.text(`Group ${g + 1}${isProcessed ? ' ✓' : ''}`);
}
// Show remaining nodes
if (remaining > 0) {
const x = startX + numFullGroups * 200;
const remainingVals = originalList.slice(numFullGroups * k);
svg.append("rect")
.attr("x", x)
.attr("y", startY + 15)
.attr("width", 100)
.attr("height", 40)
.attr("rx", 8)
.attr("fill", "#fee2e2")
.attr("stroke", "#ef4444")
.attr("stroke-dasharray", "5,5");
svg.append("text")
.attr("x", x + 50)
.attr("y", startY + 42)
.attr("text-anchor", "middle")
.attr("font-size", "14px")
.attr("fill", "#1e293b")
.text(`[${remainingVals.join(', ')}]`);
svg.append("text")
.attr("x", x + 50)
.attr("y", startY + 72)
.attr("text-anchor", "middle")
.attr("font-size", "11px")
.attr("fill", "#ef4444")
.text("< k, unchanged");
}
}
function drawAlgorithmSteps() {
const startX = 30;
const startY = 330;
svg.append("text")
.attr("x", startX)
.attr("y", startY)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("Algorithm:");
const steps = [
"1. Find kth node from current position",
"2. If k nodes exist, reverse the group",
"3. Reconnect: prev_group → reversed → next_group",
"4. Move to next group, repeat"
];
steps.forEach((step, idx) => {
svg.append("text")
.attr("x", startX)
.attr("y", startY + 25 + idx * 22)
.attr("font-size", "12px")
.attr("fill", "#64748b")
.text(step);
});
// Reversal diagram
svg.append("text")
.attr("x", 400)
.attr("y", startY)
.attr("font-size", "13px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("Reversal Process:");
svg.append("text")
.attr("x", 400)
.attr("y", startY + 25)
.attr("font-size", "12px")
.attr("fill", "#64748b")
.text("1 → 2 becomes 2 → 1");
svg.append("text")
.attr("x", 400)
.attr("y", startY + 50)
.attr("font-size", "12px")
.attr("fill", "#64748b")
.text("By reversing 'next' pointers one by one");
// Final result preview
svg.append("text")
.attr("x", startX)
.attr("y", 480)
.attr("font-size", "13px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("Expected Result:");
const expectedResult = [];
for (let g = 0; g < Math.floor(originalList.length / k); g++) {
for (let i = k - 1; i >= 0; i--) {
expectedResult.push(originalList[g * k + i]);
}
}
for (let i = Math.floor(originalList.length / k) * k; i < originalList.length; i++) {
expectedResult.push(originalList[i]);
}
svg.append("text")
.attr("x", startX + 130)
.attr("y", 480)
.attr("font-size", "13px")
.attr("fill", "#10b981")
.text(`[${expectedResult.join(' → ')}]`);
}
function step() {
const numFullGroups = Math.floor(originalList.length / k);
if (phase === 4 || reversedGroups.length >= numFullGroups) {
phase = 4;
document.getElementById("status").textContent = "✓ All groups reversed!";
return;
}
if (phase === 0) {
phase = 1;
currentGroup = [];
for (let i = 0; i < k; i++) {
currentGroup.push(groupStart + i);
}
document.getElementById("status").textContent =
`Found group at indices ${groupStart} to ${groupStart + k - 1}`;
} else if (phase === 1) {
phase = 2;
reverseIdx = 0;
document.getElementById("status").textContent =
`Reversing group [${currentGroup.map(i => originalList[i]).join(', ')}]`;
} else if (phase === 2) {
// Actually reverse the nodes in this group
const groupEndIdx = groupStart + k - 1;
// Swap positions
for (let i = 0; i < k; i++) {
const node = nodes.find(n => n.originalIdx === groupStart + i);
node.currentIdx = groupStart + (k - 1 - i);
node.reversed = true;
}
reversedGroups.push(groupStart);
phase = 3;
document.getElementById("status").textContent =
`Group reversed and reconnected`;
} else if (phase === 3) {
groupStart += k;
currentGroup = [];
if (groupStart + k <= originalList.length) {
phase = 1;
for (let i = 0; i < k; i++) {
currentGroup.push(groupStart + i);
}
document.getElementById("status").textContent =
`Moving to next group at index ${groupStart}`;
} else {
phase = 4;
document.getElementById("status").textContent =
`✓ Complete! Remaining nodes (${originalList.length - groupStart}) < k, unchanged`;
}
}
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();
}, 900);
}
document.getElementById("autoRunBtn").addEventListener("click", autoRun);
document.getElementById("stepBtn").addEventListener("click", step);
document.getElementById("resetBtn").addEventListener("click", reset);
reset();
</script>
</body>
</html>