-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0006_zigzag_conversion.html
More file actions
499 lines (422 loc) · 17.4 KB
/
0006_zigzag_conversion.html
File metadata and controls
499 lines (422 loc) · 17.4 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Zigzag Conversion - LeetCode 6</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">#6</span> Zigzag Conversion</h1>
<p>Write characters in a zigzag pattern on given number of rows, then read line by line.</p>
<div class="problem-meta">
<span class="meta-tag">String</span>
<span class="meta-tag">Medium</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0006_zigzag_conversion/0006_zigzag_conversion.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>This algorithm solves the problem <strong>step by step</strong>:</p>
<ul>
<li><strong>Understand:</strong> Parse the input data</li>
<li><strong>Process:</strong> Apply the core logic</li>
<li><strong>Optimize:</strong> Use efficient data structures</li>
<li><strong>Return:</strong> Output the computed result</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>Speed:</label>
<input type="range" id="speedSlider" min="1" max="10" value="5">
</div>
</div>
<svg id="mainSvg" width="900" height="450"></svg>
<div class="variables-display">
<div id="varDisplay"></div>
</div>
<div class="status-message" id="status">Click "Step" to see zigzag pattern</div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List
"""
LeetCode Zigzag Conversion
Problem from LeetCode: https://leetcode.com/problems/zigzag-conversion/
Description:
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this:
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows.
Example 1:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
P I N
A L S I G
Y A H R
P I
Example 3:
Input: s = "A", numRows = 1
Output: "A"
"""
class Solution:
def convert(self, s: str, numRows: int) -> str:
"""
Convert a string into a zigzag pattern and return the result read line by line.
Args:
s: Input string
numRows: Number of rows for the zigzag pattern
Returns:
str: Zigzag converted string
"""
# Handle edge cases
if numRows == 1 or numRows >= len(s):
return s
# Initialize rows
rows = [''] * numRows
# Variables to track current direction and row
index = 0
step = 1
# Traverse through the string
for char in s:
# Add current character to the current row
rows[index] += char
# Change direction if we reach the first or last row
if index == 0:
step = 1
elif index == numRows - 1:
step = -1
# Move to the next row
index += step
# Combine all rows into a single string
return ''.join(rows)
def convert_simulation(self, s: str, numRows: int) -> str:
"""
Alternative implementation that uses a more visual approach.
Args:
s: Input string
numRows: Number of rows for the zigzag pattern
Returns:
str: Zigzag converted string
"""
if numRows == 1 or numRows >= len(s):
return s
# Calculate the cycle length
cycle_len = 2 * numRows - 2
result = []
for i in range(numRows):
for j in range(i, len(s), cycle_len):
# Add the character at the current position
result.append(s[j])
# Add the character at the corresponding position in the same cycle
# This is only applicable for rows other than the first and last
if i != 0 and i != numRows - 1 and j + cycle_len - 2 * i < len(s):
result.append(s[j + cycle_len - 2 * i])
return ''.join(result)
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
s1 = "PAYPALISHIRING"
numRows1 = 3
result1 = solution.convert(s1, numRows1)
print(f"Example 1: '{s1}' with {numRows1} rows -> '{result1}'") # Expected: "PAHNAPLSIIGYIR"
# Example 2
s2 = "PAYPALISHIRING"
numRows2 = 4
result2 = solution.convert(s2, numRows2)
print(f"Example 2: '{s2}' with {numRows2} rows -> '{result2}'") # Expected: "PINALSIGYAHRPI"
# Example 3
s3 = "A"
numRows3 = 1
result3 = solution.convert(s3, numRows3)
print(f"Example 3: '{s3}' with {numRows3} rows -> '{result3}'") # Expected: "A"
</pre>
</div>
</div>
</div>
<script>
const inputString = "PAYPALISHIRING";
const numRows = 4;
const width = 900, height = 450;
const svg = d3.select("#mainSvg");
// State variables
let charIndex = 0;
let rowIndex = 0;
let direction = 1; // 1 = down, -1 = up
let rows = Array(numRows).fill(null).map(() => []);
let positions = [];
let autoTimer = null;
let autoRunning = false;
const cellWidth = 50;
const cellHeight = 55;
const startX = 120;
const startY = 80;
function draw() {
svg.selectAll("*").remove();
// Title
svg.append("text")
.attr("x", width / 2)
.attr("y", 35)
.attr("text-anchor", "middle")
.attr("font-weight", "bold")
.attr("font-size", "16px")
.text(`Zigzag: "${inputString}" with ${numRows} rows`);
// Draw input string at top
svg.append("text")
.attr("x", 20)
.attr("y", 60)
.attr("font-size", "12px")
.attr("fill", "#666")
.text("Input:");
for (let i = 0; i < inputString.length; i++) {
const isProcessed = i < charIndex;
const isCurrent = i === charIndex;
svg.append("rect")
.attr("x", 70 + i * 30)
.attr("y", 45)
.attr("width", 26)
.attr("height", 26)
.attr("rx", 4)
.attr("fill", isCurrent ? "#fef3c7" : isProcessed ? "#d1d5db" : "#e0e7ff")
.attr("stroke", isCurrent ? "#f59e0b" : "#6366f1")
.attr("stroke-width", isCurrent ? 2 : 1);
svg.append("text")
.attr("x", 70 + i * 30 + 13)
.attr("y", 63)
.attr("text-anchor", "middle")
.attr("font-size", "14px")
.attr("font-weight", isCurrent ? "bold" : "normal")
.attr("fill", isProcessed && !isCurrent ? "#9ca3af" : "#1f2937")
.text(inputString[i]);
}
// Draw row labels
for (let row = 0; row < numRows; row++) {
const isCurrentRow = row === rowIndex && charIndex < inputString.length;
svg.append("text")
.attr("x", 20)
.attr("y", startY + row * cellHeight + 30)
.attr("font-size", "14px")
.attr("font-weight", isCurrentRow ? "bold" : "normal")
.attr("fill", isCurrentRow ? "#6366f1" : "#666")
.text(`Row ${row}:`);
// Draw row highlight
if (isCurrentRow) {
svg.append("rect")
.attr("x", startX - 10)
.attr("y", startY + row * cellHeight)
.attr("width", (positions.filter(p => p.row === row).length + 1) * cellWidth + 20)
.attr("height", cellHeight)
.attr("rx", 6)
.attr("fill", "#eef2ff")
.attr("opacity", 0.5);
}
}
// Draw placed characters with animations
positions.forEach((pos, idx) => {
const x = startX + pos.colInRow * cellWidth;
const y = startY + pos.row * cellHeight;
const isCurrent = idx === positions.length - 1;
const rect = svg.append("rect")
.attr("x", x)
.attr("y", y)
.attr("width", cellWidth - 8)
.attr("height", cellHeight - 10)
.attr("rx", 8)
.attr("fill", isCurrent ? "#fef3c7" : "#e0e7ff")
.attr("stroke", isCurrent ? "#f59e0b" : "#6366f1")
.attr("stroke-width", isCurrent ? 3 : 2);
// Animate new elements
if (isCurrent) {
rect.attr("opacity", 0)
.transition()
.duration(300)
.attr("opacity", 1);
}
const text = svg.append("text")
.attr("x", x + (cellWidth - 8) / 2)
.attr("y", y + (cellHeight - 10) / 2 + 6)
.attr("text-anchor", "middle")
.attr("font-size", "22px")
.attr("font-weight", "bold")
.attr("fill", "#1f2937")
.text(pos.char);
if (isCurrent) {
text.attr("opacity", 0)
.transition()
.duration(300)
.attr("opacity", 1);
}
});
// Draw zigzag path lines
if (positions.length >= 2) {
for (let i = 1; i < positions.length; i++) {
const prev = positions[i - 1];
const curr = positions[i];
const x1 = startX + prev.colInRow * cellWidth + (cellWidth - 8) / 2;
const y1 = startY + prev.row * cellHeight + (cellHeight - 10) / 2;
const x2 = startX + curr.colInRow * cellWidth + (cellWidth - 8) / 2;
const y2 = startY + curr.row * cellHeight + (cellHeight - 10) / 2;
svg.append("line")
.attr("x1", x1)
.attr("y1", y1)
.attr("x2", x2)
.attr("y2", y2)
.attr("stroke", "#cbd5e1")
.attr("stroke-width", 2)
.attr("stroke-dasharray", "4,4")
.attr("opacity", 0.7);
}
}
// Draw direction indicator
if (charIndex < inputString.length) {
const arrowY = startY + rowIndex * cellHeight + (cellHeight - 10) / 2;
const arrowX = startX - 50;
svg.append("text")
.attr("x", arrowX)
.attr("y", arrowY + 5)
.attr("font-size", "20px")
.attr("fill", direction > 0 ? "#10b981" : "#f59e0b")
.text(direction > 0 ? "↓" : "↑");
}
// Draw result section
const resultY = startY + numRows * cellHeight + 30;
svg.append("text")
.attr("x", 20)
.attr("y", resultY)
.attr("font-weight", "bold")
.attr("font-size", "14px")
.text("Result (read rows left to right):");
// Draw each row's contribution to result
let resultX = 220;
for (let row = 0; row < numRows; row++) {
const rowChars = positions.filter(p => p.row === row).map(p => p.char);
if (rowChars.length > 0) {
svg.append("text")
.attr("x", resultX)
.attr("y", resultY)
.attr("font-size", "16px")
.attr("fill", "#059669")
.attr("font-weight", "bold")
.text(rowChars.join(""));
resultX += rowChars.length * 14 + 5;
}
}
// Full result string
const fullResult = [];
for (let row = 0; row < numRows; row++) {
const rowChars = positions.filter(p => p.row === row).map(p => p.char);
fullResult.push(...rowChars);
}
svg.append("text")
.attr("x", 20)
.attr("y", resultY + 30)
.attr("font-size", "12px")
.attr("fill", "#666")
.text(`Full Result: "${fullResult.join("")}"`);
// Update variables display
updateVariables();
}
function updateVariables() {
const remaining = inputString.substring(charIndex);
document.getElementById("varDisplay").innerHTML = `
<span class="var-item">Current Index: ${charIndex}</span>
<span class="var-item">Current Row: ${rowIndex}</span>
<span class="var-item">Direction: ${direction > 0 ? "Down ↓" : "Up ↑"}</span>
<span class="var-item">Remaining: "${remaining}"</span>
`;
}
function doStep() {
if (charIndex >= inputString.length) {
const result = [];
for (let row = 0; row < numRows; row++) {
const rowChars = positions.filter(p => p.row === row).map(p => p.char);
result.push(...rowChars);
}
document.getElementById("status").textContent =
`✓ Done! Result: "${result.join("")}"`;
return false;
}
const char = inputString[charIndex];
const colInRow = positions.filter(p => p.row === rowIndex).length;
// Add character to current row
rows[rowIndex].push(char);
positions.push({
char,
row: rowIndex,
colInRow: colInRow,
index: charIndex
});
document.getElementById("status").textContent =
`Placing '${char}' at Row ${rowIndex}. Moving ${direction > 0 ? 'down ↓' : 'up ↑'}`;
// Update direction at boundaries
if (rowIndex === 0) {
direction = 1;
} else if (rowIndex === numRows - 1) {
direction = -1;
}
// Move to next row
rowIndex += direction;
charIndex++;
draw();
return charIndex < inputString.length;
}
function reset() {
charIndex = 0;
rowIndex = 0;
direction = 1;
rows = Array(numRows).fill(null).map(() => []);
positions = [];
stopAuto();
document.getElementById("status").textContent = 'Click "Step" to see zigzag pattern';
draw();
}
function stopAuto() {
if (autoTimer) {
clearInterval(autoTimer);
autoTimer = null;
}
autoRunning = false;
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;
autoTimer = setInterval(() => {
if (!doStep()) {
stopAuto();
}
}, speed * 150);
}
}
// Event listeners
document.getElementById("stepBtn").addEventListener("click", doStep);
document.getElementById("autoBtn").addEventListener("click", toggleAuto);
document.getElementById("resetBtn").addEventListener("click", reset);
// Initial draw
draw();
</script>
</body>
</html>