-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0088_merge_sorted_array.html
More file actions
644 lines (567 loc) · 24.1 KB
/
0088_merge_sorted_array.html
File metadata and controls
644 lines (567 loc) · 24.1 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>088 - Merge Sorted Array</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">#088</span> Merge Sorted Array</h1>
<p>
Given two integer arrays nums1 and nums2, sorted in non-decreasing order, merge
nums2 into nums1 as one sorted array. The number of elements initialized in nums1
is m, and in nums2 is n. nums1 has enough space to hold m + n elements.
</p>
<h3>Key Insight</h3>
<p>
Merge from the end! Start filling nums1 from the back (position m+n-1) by
comparing the largest remaining elements from both arrays. This avoids
overwriting elements we haven't processed yet.
</p>
<div class="problem-meta">
<span class="meta-tag">📊 Array</span>
<span class="meta-tag">📊 Sorting</span>
<span class="meta-tag">⏱️ O(n log n)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0088_merge_sorted_array/0088_merge_sorted_array.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 merge arrays from the end</div>
<svg id="visualization"></svg>
</section>
<section class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List
"""
LeetCode Merge Sorted Array
Problem from LeetCode: https://leetcode.com/problems/merge-sorted-array/
Description:
You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.
Merge nums1 and nums2 into a single array sorted in non-decreasing order.
The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.
Example 1:
Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
Explanation: The arrays we are merging are [1,2,3] and [2,5,6].
The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.
Example 2:
Input: nums1 = [1], m = 1, nums2 = [], n = 0
Output: [1]
Explanation: The arrays we are merging are [1] and [].
The result of the merge is [1].
Example 3:
Input: nums1 = [0], m = 0, nums2 = [1], n = 1
Output: [1]
Explanation: The arrays we are merging are [] and [1].
The result of the merge is [1].
Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.
"""
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Merge nums1 and nums2 into a single sorted array in-place.
Fills nums1 with the result of the merge.
Args:
nums1: First sorted array with extra space at the end
m: Number of elements in nums1
nums2: Second sorted array
n: Number of elements in nums2
"""
# Start from the end of both arrays
i, j, k = m - 1, n - 1, m + n - 1
# While there are elements in both arrays
while i >= 0 and j >= 0:
# Place the larger element at the end of nums1
if nums1[i] > nums2[j]:
nums1[k] = nums1[i]
i -= 1
else:
nums1[k] = nums2[j]
j -= 1
k -= 1
# If there are remaining elements in nums2, add them to nums1
# (No need to check nums1 as those elements are already in place)
while j >= 0:
nums1[k] = nums2[j]
j -= 1
k -= 1
def merge_pythonic(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
A more pythonic solution using slicing.
Args:
nums1: First sorted array with extra space at the end
m: Number of elements in nums1
nums2: Second sorted array
n: Number of elements in nums2
"""
# Replace the trailing zeros in nums1 with nums2 elements
nums1[m:] = nums2[:n]
# Sort the entire array
nums1.sort()
def merge_two_pointers(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Alternative approach using two pointers from the beginning of each array.
Uses a temporary array to store results, then copies back to nums1.
Args:
nums1: First sorted array with extra space at the end
m: Number of elements in nums1
nums2: Second sorted array
n: Number of elements in nums2
"""
# Create a copy of the first m elements of nums1
nums1_copy = nums1[:m]
# Pointers for nums1_copy and nums2
p1, p2 = 0, 0
# Merge elements back into nums1
for p in range(m + n):
# If we've exhausted nums1_copy or if nums2 element is smaller
if p1 >= m or (p2 < n and nums2[p2] < nums1_copy[p1]):
nums1[p] = nums2[p2]
p2 += 1
else:
nums1[p] = nums1_copy[p1]
p1 += 1
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
nums1_1 = [1, 2, 3, 0, 0, 0]
m1 = 3
nums2_1 = [2, 5, 6]
n1 = 3
solution.merge(nums1_1, m1, nums2_1, n1)
print(f"Example 1: {nums1_1}") # Expected output: [1, 2, 2, 3, 5, 6]
# Example 2
nums1_2 = [1]
m2 = 1
nums2_2 = []
n2 = 0
solution.merge(nums1_2, m2, nums2_2, n2)
print(f"Example 2: {nums1_2}") # Expected output: [1]
# Example 3
nums1_3 = [0]
m3 = 0
nums2_3 = [1]
n3 = 1
solution.merge(nums1_3, m3, nums2_3, n3)
print(f"Example 3: {nums1_3}") # Expected output: [1]
# Compare with other implementations
nums1_4 = [1, 2, 3, 0, 0, 0]
solution.merge_pythonic(nums1_4, 3, [2, 5, 6], 3)
print(f"\nPythonic approach: {nums1_4}") # Expected output: [1, 2, 2, 3, 5, 6]
nums1_5 = [1, 2, 3, 0, 0, 0]
solution.merge_two_pointers(nums1_5, 3, [2, 5, 6], 3)
print(f"Two-pointers approach: {nums1_5}") # Expected output: [1, 2, 2, 3, 5, 6]
</pre>
</div>
</section>
</div>
<script>
const width = 900;
const height = 550;
const svg = d3.select("#visualization")
.attr("width", width)
.attr("height", height);
// Example data
const originalNums1 = [1, 2, 3, 0, 0, 0];
const originalNums2 = [2, 5, 6];
const m = 3;
const n = 3;
let nums1 = [];
let nums2 = [];
let i, j, k;
let phase = "init";
let animationTimer = null;
let comparing = null;
let history = [];
function reset() {
nums1 = [...originalNums1];
nums2 = [...originalNums2];
i = m - 1;
j = n - 1;
k = m + n - 1;
phase = "init";
comparing = null;
history = [];
if (animationTimer) clearInterval(animationTimer);
animationTimer = null;
document.getElementById("autoRunBtn").textContent = "▶ Auto Run";
document.getElementById("status").textContent =
`Merge from the end: i=${i} (nums1), j=${j} (nums2), k=${k} (insert position)`;
render();
}
function render() {
svg.selectAll("*").remove();
const cellWidth = 60;
const cellHeight = 50;
const startX = 80;
const nums1Y = 100;
const nums2Y = 200;
// Title and explanation
svg.append("text")
.attr("x", 30)
.attr("y", 35)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("Merge from End Strategy: Fill nums1 backwards, comparing largest elements");
// nums1 label
svg.append("text")
.attr("x", 30)
.attr("y", nums1Y + 30)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("nums1:");
// Draw nums1
nums1.forEach((val, idx) => {
const x = startX + idx * cellWidth;
const isOriginal = idx < m && nums1[idx] === originalNums1[idx];
const isZeroSlot = originalNums1[idx] === 0 && idx >= m;
const isCurrent = idx === k;
const isComparing = idx === i && comparing !== null;
const isFilled = !isZeroSlot || nums1[idx] !== 0;
svg.append("rect")
.attr("x", x)
.attr("y", nums1Y)
.attr("width", cellWidth - 5)
.attr("height", cellHeight)
.attr("rx", 8)
.attr("fill", () => {
if (isCurrent) return "#fef3c7";
if (isComparing) return "#dbeafe";
if (isFilled && idx >= m) return "#d1fae5";
if (isZeroSlot && !isFilled) return "#f1f5f9";
return "#e0e7ff";
})
.attr("stroke", () => {
if (isCurrent) return "#f59e0b";
if (isComparing) return "#3b82f6";
if (isFilled && idx >= m) return "#10b981";
return "#6366f1";
})
.attr("stroke-width", isCurrent || isComparing ? 3 : 2);
svg.append("text")
.attr("x", x + (cellWidth - 5) / 2)
.attr("y", nums1Y + 32)
.attr("text-anchor", "middle")
.attr("font-size", "18px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text(val === 0 && idx >= m && originalNums1[idx] === 0 && nums1[idx] === 0 ? "-" : val);
// Index labels
svg.append("text")
.attr("x", x + (cellWidth - 5) / 2)
.attr("y", nums1Y + cellHeight + 20)
.attr("text-anchor", "middle")
.attr("font-size", "11px")
.attr("fill", "#64748b")
.text(idx);
});
// Pointer indicators for nums1
if (i >= 0 && phase !== "done") {
svg.append("text")
.attr("x", startX + i * cellWidth + (cellWidth - 5) / 2)
.attr("y", nums1Y - 15)
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.attr("font-weight", "bold")
.attr("fill", "#3b82f6")
.text("i");
svg.append("path")
.attr("d", `M${startX + i * cellWidth + (cellWidth - 5) / 2},${nums1Y - 10} L${startX + i * cellWidth + (cellWidth - 5) / 2},${nums1Y - 3}`)
.attr("stroke", "#3b82f6")
.attr("stroke-width", 2)
.attr("marker-end", "url(#arrowBlue)");
}
if (k >= 0 && phase !== "done") {
svg.append("text")
.attr("x", startX + k * cellWidth + (cellWidth - 5) / 2)
.attr("y", nums1Y + cellHeight + 45)
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.attr("font-weight", "bold")
.attr("fill", "#f59e0b")
.text("k (insert)");
}
// nums2 label
svg.append("text")
.attr("x", 30)
.attr("y", nums2Y + 30)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("nums2:");
// Draw nums2
nums2.forEach((val, idx) => {
const x = startX + idx * cellWidth;
const isComparing = idx === j && comparing !== null;
const isUsed = idx > j;
svg.append("rect")
.attr("x", x)
.attr("y", nums2Y)
.attr("width", cellWidth - 5)
.attr("height", cellHeight)
.attr("rx", 8)
.attr("fill", () => {
if (isUsed) return "#f1f5f9";
if (isComparing) return "#dbeafe";
return "#fce7f3";
})
.attr("stroke", () => {
if (isUsed) return "#94a3b8";
if (isComparing) return "#3b82f6";
return "#ec4899";
})
.attr("stroke-width", isComparing ? 3 : 2)
.attr("opacity", isUsed ? 0.5 : 1);
svg.append("text")
.attr("x", x + (cellWidth - 5) / 2)
.attr("y", nums2Y + 32)
.attr("text-anchor", "middle")
.attr("font-size", "18px")
.attr("font-weight", "bold")
.attr("fill", isUsed ? "#94a3b8" : "#1e293b")
.text(val);
// Index labels
svg.append("text")
.attr("x", x + (cellWidth - 5) / 2)
.attr("y", nums2Y + cellHeight + 20)
.attr("text-anchor", "middle")
.attr("font-size", "11px")
.attr("fill", "#64748b")
.text(idx);
});
// Pointer for nums2
if (j >= 0 && phase !== "done") {
svg.append("text")
.attr("x", startX + j * cellWidth + (cellWidth - 5) / 2)
.attr("y", nums2Y - 15)
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.attr("font-weight", "bold")
.attr("fill", "#ec4899")
.text("j");
svg.append("path")
.attr("d", `M${startX + j * cellWidth + (cellWidth - 5) / 2},${nums2Y - 10} L${startX + j * cellWidth + (cellWidth - 5) / 2},${nums2Y - 3}`)
.attr("stroke", "#ec4899")
.attr("stroke-width", 2)
.attr("marker-end", "url(#arrowPink)");
}
// Arrow markers
const defs = svg.append("defs");
defs.append("marker")
.attr("id", "arrowBlue")
.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", "#3b82f6");
defs.append("marker")
.attr("id", "arrowPink")
.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", "#ec4899");
// Algorithm explanation
const algoY = 320;
svg.append("text")
.attr("x", 30)
.attr("y", algoY)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("Algorithm Steps:");
const steps = [
"1. Start with i at end of nums1 elements, j at end of nums2, k at last position",
"2. Compare nums1[i] and nums2[j], place larger at nums1[k]",
"3. Decrement the pointer of the array we took from, and k",
"4. When one array is exhausted, copy remaining from the other"
];
steps.forEach((step, idx) => {
svg.append("text")
.attr("x", 30)
.attr("y", algoY + 25 + idx * 22)
.attr("font-size", "12px")
.attr("fill", "#64748b")
.text(step);
});
// Current comparison
if (comparing && phase === "compare") {
const compY = 440;
svg.append("rect")
.attr("x", 30)
.attr("y", compY)
.attr("width", 350)
.attr("height", 50)
.attr("rx", 10)
.attr("fill", "#eff6ff")
.attr("stroke", "#3b82f6");
svg.append("text")
.attr("x", 205)
.attr("y", compY + 32)
.attr("text-anchor", "middle")
.attr("font-size", "14px")
.attr("fill", "#1e293b")
.text(comparing);
}
// Final result
if (phase === "done") {
svg.append("rect")
.attr("x", 30)
.attr("y", 440)
.attr("width", 500)
.attr("height", 55)
.attr("rx", 10)
.attr("fill", "#d1fae5")
.attr("stroke", "#10b981")
.attr("stroke-width", 2);
svg.append("text")
.attr("x", 280)
.attr("y", 475)
.attr("text-anchor", "middle")
.attr("font-size", "18px")
.attr("font-weight", "bold")
.attr("fill", "#10b981")
.text(`✓ Merged! Result: [${nums1.join(', ')}]`);
}
// Legend
const legendX = 550;
const legendY = 320;
svg.append("text")
.attr("x", legendX)
.attr("y", legendY)
.attr("font-size", "13px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("Legend:");
const legendItems = [
{ color: "#e0e7ff", stroke: "#6366f1", text: "Original nums1" },
{ color: "#fce7f3", stroke: "#ec4899", text: "nums2" },
{ color: "#d1fae5", stroke: "#10b981", text: "Filled position" },
{ color: "#fef3c7", stroke: "#f59e0b", text: "Insert position (k)" }
];
legendItems.forEach((item, idx) => {
svg.append("rect")
.attr("x", legendX)
.attr("y", legendY + 15 + idx * 28)
.attr("width", 20)
.attr("height", 20)
.attr("rx", 4)
.attr("fill", item.color)
.attr("stroke", item.stroke);
svg.append("text")
.attr("x", legendX + 30)
.attr("y", legendY + 30 + idx * 28)
.attr("font-size", "12px")
.attr("fill", "#64748b")
.text(item.text);
});
}
function step() {
if (phase === "done") return;
if (phase === "init") {
phase = "compare";
}
if (i >= 0 && j >= 0) {
// Compare and place
if (nums1[i] > nums2[j]) {
comparing = `nums1[${i}]=${nums1[i]} > nums2[${j}]=${nums2[j]} → Place ${nums1[i]} at position ${k}`;
nums1[k] = nums1[i];
i--;
} else {
comparing = `nums1[${i}]=${nums1[i]} <= nums2[${j}]=${nums2[j]} → Place ${nums2[j]} at position ${k}`;
nums1[k] = nums2[j];
j--;
}
k--;
if (i < 0 && j < 0) {
phase = "done";
document.getElementById("status").textContent = "✓ Merge complete!";
} else if (i < 0) {
document.getElementById("status").textContent =
`nums1 exhausted, copying remaining from nums2. j=${j}, k=${k}`;
} else if (j < 0) {
phase = "done";
document.getElementById("status").textContent =
"✓ nums2 exhausted, nums1 elements already in place!";
} else {
document.getElementById("status").textContent =
`Next: compare nums1[${i}]=${nums1[i]} and nums2[${j}]=${nums2[j]}`;
}
} else if (j >= 0) {
// Copy remaining from nums2
comparing = `Copying nums2[${j}]=${nums2[j]} to position ${k}`;
nums1[k] = nums2[j];
j--;
k--;
if (j < 0) {
phase = "done";
document.getElementById("status").textContent = "✓ Merge complete!";
} else {
document.getElementById("status").textContent =
`Copying remaining from nums2. j=${j}, k=${k}`;
}
} else {
phase = "done";
document.getElementById("status").textContent = "✓ Merge complete!";
}
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 === "done") {
clearInterval(animationTimer);
animationTimer = null;
document.getElementById("autoRunBtn").textContent = "▶ Auto Run";
return;
}
step();
}, 1000);
}
document.getElementById("autoRunBtn").addEventListener("click", autoRun);
document.getElementById("stepBtn").addEventListener("click", step);
document.getElementById("resetBtn").addEventListener("click", reset);
reset();
</script>
</body>
</html>