-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0097_interleaving_string.html
More file actions
603 lines (509 loc) · 21.1 KB
/
0097_interleaving_string.html
File metadata and controls
603 lines (509 loc) · 21.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>097 - Interleaving String</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">#097</span> Interleaving String</h1>
<p>
Check if s3 is formed by interleaving s1 and s2. Uses 2D DP where dp[i][j]
represents whether s3[0:i+j] can be formed by interleaving s1[0:i] and s2[0:j].
</p>
<div class="problem-meta">
<span class="meta-tag">🔤 String</span>
<span class="meta-tag">🧮 DP</span>
<span class="meta-tag">⏱️ O(n)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0097_interleaving_string/0097_interleaving_string.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>
<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 check interleaving</div>
<svg id="visualization"></svg>
</section>
<section class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import Dict
"""
LeetCode Interleaving String
Problem from LeetCode: https://leetcode.com/problems/interleaving-string/
Description:
Given strings s1, s2, and s3, find whether s3 is formed by an interleaving of s1 and s2.
An interleaving of two strings s and t is a configuration where s and t are divided into n and m substrings respectively, such that:
- s = s1 + s2 + ... + sn
- t = t1 + t2 + ... + tm
- |n - m| <= 1
- The interleaving is s1 + t1 + s2 + t2 + s3 + t3 + ... or t1 + s1 + t2 + s2 + t3 + s3 + ...
Note: a + b is the concatenation of strings a and b.
Example 1:
Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
Output: true
Explanation: One way to obtain s3 is:
Split s1 into s1 = "aa" + "bc" + "c", and s2 into s2 = "dbbc" + "a".
Interleaving the two splits, we get "aa" + "dbbc" + "bc" + "a" + "c" = "aadbbcbcac".
Example 2:
Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
Output: false
Explanation: Notice how it is impossible to interleave s2 with any other string to obtain s3.
Example 3:
Input: s1 = "", s2 = "", s3 = ""
Output: true
"""
class Solution:
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
"""
Determine if s3 is formed by interleaving s1 and s2.
Uses dynamic programming with a 2D table.
Args:
s1: First string
s2: Second string
s3: Target string
Returns:
bool: True if s3 is an interleaving of s1 and s2, False otherwise
"""
m, n = len(s1), len(s2)
# Quick check: s3 must have length equal to s1 + s2
if len(s3) != m + n:
return False
# dp[i][j] represents whether s3[0:i+j] is an interleaving of s1[0:i] and s2[0:j]
dp = [[False] * (n + 1) for _ in range(m + 1)]
# Base case: empty strings
dp[0][0] = True
# Fill the first row (s1 is empty)
for j in range(1, n + 1):
dp[0][j] = dp[0][j-1] and s2[j-1] == s3[j-1]
# Fill the first column (s2 is empty)
for i in range(1, m + 1):
dp[i][0] = dp[i-1][0] and s1[i-1] == s3[i-1]
# Fill the rest of the table
for i in range(1, m + 1):
for j in range(1, n + 1):
# Current character in s3
curr = s3[i+j-1]
# Can we match with s1?
match_s1 = dp[i-1][j] and s1[i-1] == curr
# Can we match with s2?
match_s2 = dp[i][j-1] and s2[j-1] == curr
dp[i][j] = match_s1 or match_s2
return dp[m][n]
def isInterleave_1d(self, s1: str, s2: str, s3: str) -> bool:
"""
Space-optimized version using 1D dynamic programming.
Args:
s1: First string
s2: Second string
s3: Target string
Returns:
bool: True if s3 is an interleaving of s1 and s2, False otherwise
"""
m, n = len(s1), len(s2)
if len(s3) != m + n:
return False
# Use a 1D array to save space
dp = [False] * (n + 1)
# Initialize
dp[0] = True
# Initial row where s1 is empty
for j in range(1, n + 1):
dp[j] = dp[j-1] and s2[j-1] == s3[j-1]
# Fill dp array row by row
for i in range(1, m + 1):
dp[0] = dp[0] and s1[i-1] == s3[i-1]
for j in range(1, n + 1):
curr = s3[i+j-1]
dp[j] = (dp[j] and s1[i-1] == curr) or (dp[j-1] and s2[j-1] == curr)
return dp[n]
def isInterleave_memo(self, s1: str, s2: str, s3: str) -> bool:
"""
Memoization-based approach using recursion.
Args:
s1: First string
s2: Second string
s3: Target string
Returns:
bool: True if s3 is an interleaving of s1 and s2, False otherwise
"""
if len(s1) + len(s2) != len(s3):
return False
memo = {}
def dp(i: int, j: int) -> bool:
"""Recursive helper function with memoization."""
# Base case: reached end of both strings
if i == len(s1) and j == len(s2):
return True
# Check if this state has been computed before
if (i, j) in memo:
return memo[(i, j)]
# Current position in s3
k = i + j
# Try to match with s1
if i < len(s1) and s1[i] == s3[k] and dp(i + 1, j):
memo[(i, j)] = True
return True
# Try to match with s2
if j < len(s2) and s2[j] == s3[k] and dp(i, j + 1):
memo[(i, j)] = True
return True
memo[(i, j)] = False
return False
return dp(0, 0)
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
s1_1 = "aabcc"
s2_1 = "dbbca"
s3_1 = "aadbbcbcac"
result1 = solution.isInterleave(s1_1, s2_1, s3_1)
print(f"Example 1: s1='{s1_1}', s2='{s2_1}', s3='{s3_1}'")
print(f"Result: {result1}") # Expected output: True
# Example 2
s1_2 = "aabcc"
s2_2 = "dbbca"
s3_2 = "aadbbbaccc"
result2 = solution.isInterleave(s1_2, s2_2, s3_2)
print(f"\nExample 2: s1='{s1_2}', s2='{s2_2}', s3='{s3_2}'")
print(f"Result: {result2}") # Expected output: False
# Example 3
s1_3 = ""
s2_3 = ""
s3_3 = ""
result3 = solution.isInterleave(s1_3, s2_3, s3_3)
print(f"\nExample 3: s1='{s1_3}', s2='{s2_3}', s3='{s3_3}'")
print(f"Result: {result3}") # Expected output: True
# Compare with other approaches
print("\nUsing 1D dynamic programming approach:")
print(f"Example 1: {solution.isInterleave_1d(s1_1, s2_1, s3_1)}")
print(f"Example 2: {solution.isInterleave_1d(s1_2, s2_2, s3_2)}")
print("\nUsing memoization approach:")
print(f"Example 1: {solution.isInterleave_memo(s1_1, s2_1, s3_1)}")
print(f"Example 2: {solution.isInterleave_memo(s1_2, s2_2, s3_2)}")
</pre>
</div>
</section>
</div>
<script>
const width = 900;
const height = 600;
const svg = d3.select("#visualization")
.attr("width", width)
.attr("height", height);
const s1 = "aab";
const s2 = "axy";
const s3 = "aaxaby";
const m = s1.length;
const n = s2.length;
let dp = [];
let currentI = 0;
let currentJ = 0;
let phase = 0; // 0: init, 1: first row, 2: first col, 3: fill, 4: done
let animationTimer = null;
function reset() {
dp = Array(m + 1).fill(null).map(() => Array(n + 1).fill(null));
currentI = 0;
currentJ = 0;
phase = 0;
if (animationTimer) clearInterval(animationTimer);
document.getElementById("status").textContent =
`Checking if "${s3}" is interleaving of "${s1}" and "${s2}"`;
render();
}
function render() {
svg.selectAll("*").remove();
const cellSize = 50;
const startX = 120;
const startY = 120;
// Draw strings
drawStrings();
// Draw DP table
drawDPTable(startX, startY, cellSize);
// Draw s3 matching
drawS3Matching();
}
function drawStrings() {
// s1 (vertical)
svg.append("text")
.attr("x", 20)
.attr("y", 30)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text(`s1 = "${s1}"`);
// s2 (horizontal)
svg.append("text")
.attr("x", 120)
.attr("y", 30)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text(`s2 = "${s2}"`);
// s3
svg.append("text")
.attr("x", 250)
.attr("y", 30)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text(`s3 = "${s3}"`);
}
function drawDPTable(startX, startY, cellSize) {
// Column headers (s2)
svg.append("text")
.attr("x", startX + cellSize / 2)
.attr("y", startY - 30)
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.attr("fill", "#64748b")
.text("ε");
for (let j = 0; j < n; j++) {
svg.append("text")
.attr("x", startX + (j + 1) * cellSize + cellSize / 2)
.attr("y", startY - 30)
.attr("text-anchor", "middle")
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#3b82f6")
.text(s2[j]);
}
// Row headers (s1)
svg.append("text")
.attr("x", startX - 20)
.attr("y", startY + cellSize / 2 + 5)
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.attr("fill", "#64748b")
.text("ε");
for (let i = 0; i < m; i++) {
svg.append("text")
.attr("x", startX - 20)
.attr("y", startY + (i + 1) * cellSize + cellSize / 2 + 5)
.attr("text-anchor", "middle")
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#10b981")
.text(s1[i]);
}
// Draw cells
for (let i = 0; i <= m; i++) {
for (let j = 0; j <= n; j++) {
const x = startX + j * cellSize;
const y = startY + i * cellSize;
const value = dp[i][j];
const isCurrent = i === currentI && j === currentJ && phase > 0 && phase < 4;
svg.append("rect")
.attr("x", x)
.attr("y", y)
.attr("width", cellSize - 2)
.attr("height", cellSize - 2)
.attr("rx", 4)
.attr("fill", () => {
if (isCurrent) return "#fef3c7";
if (value === true) return "#d1fae5";
if (value === false) return "#fee2e2";
return "#f8fafc";
})
.attr("stroke", () => {
if (isCurrent) return "#f59e0b";
if (value === true) return "#10b981";
if (value === false) return "#ef4444";
return "#e2e8f0";
})
.attr("stroke-width", isCurrent ? 3 : 1);
if (value !== null) {
svg.append("text")
.attr("x", x + cellSize / 2 - 1)
.attr("y", y + cellSize / 2 + 5)
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.attr("font-weight", "bold")
.attr("fill", value ? "#10b981" : "#ef4444")
.text(value ? "T" : "F");
}
}
}
// Index labels
svg.append("text")
.attr("x", startX - 50)
.attr("y", startY - 50)
.attr("font-size", "12px")
.attr("fill", "#64748b")
.text("dp[i][j]");
}
function drawS3Matching() {
const startX = 450;
const startY = 100;
svg.append("text")
.attr("x", startX)
.attr("y", startY - 20)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("Target s3:");
s3.split('').forEach((ch, idx) => {
const x = startX + (idx % 6) * 45;
const y = startY + Math.floor(idx / 6) * 50;
const matchedUpTo = phase === 4 ? s3.length : currentI + currentJ;
const isMatched = idx < matchedUpTo && phase > 0;
svg.append("rect")
.attr("x", x)
.attr("y", y)
.attr("width", 40)
.attr("height", 40)
.attr("rx", 6)
.attr("fill", isMatched ? "#d1fae5" : "#f8fafc")
.attr("stroke", isMatched ? "#10b981" : "#94a3b8")
.attr("stroke-width", 2);
svg.append("text")
.attr("x", x + 20)
.attr("y", y + 27)
.attr("text-anchor", "middle")
.attr("font-size", "18px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text(ch);
svg.append("text")
.attr("x", x + 20)
.attr("y", y + 55)
.attr("text-anchor", "middle")
.attr("font-size", "10px")
.attr("fill", "#64748b")
.text(idx);
});
// Explanation
svg.append("text")
.attr("x", startX)
.attr("y", 280)
.attr("font-size", "12px")
.attr("fill", "#64748b")
.text("dp[i][j] = true if s3[0:i+j] can be");
svg.append("text")
.attr("x", startX)
.attr("y", 300)
.attr("font-size", "12px")
.attr("fill", "#64748b")
.text("formed by interleaving s1[0:i] and s2[0:j]");
svg.append("text")
.attr("x", startX)
.attr("y", 340)
.attr("font-size", "12px")
.attr("fill", "#10b981")
.text("• Match from s1: dp[i-1][j] && s1[i-1] == s3[i+j-1]");
svg.append("text")
.attr("x", startX)
.attr("y", 360)
.attr("font-size", "12px")
.attr("fill", "#3b82f6")
.text("• Match from s2: dp[i][j-1] && s2[j-1] == s3[i+j-1]");
}
function step() {
if (phase === 4) {
const result = dp[m][n];
document.getElementById("status").textContent =
`✓ Complete! "${s3}" ${result ? "IS" : "is NOT"} an interleaving of "${s1}" and "${s2}"`;
return;
}
if (phase === 0) {
// Initialize dp[0][0]
dp[0][0] = true;
phase = 1;
currentI = 0;
currentJ = 1;
document.getElementById("status").textContent =
"dp[0][0] = true (empty strings match empty s3 prefix)";
} else if (phase === 1) {
// Fill first row (s1 empty)
if (currentJ <= n) {
dp[0][currentJ] = dp[0][currentJ - 1] && s2[currentJ - 1] === s3[currentJ - 1];
document.getElementById("status").textContent =
`dp[0][${currentJ}]: s2[${currentJ-1}]='${s2[currentJ-1]}' vs s3[${currentJ-1}]='${s3[currentJ-1]}' → ${dp[0][currentJ]}`;
currentJ++;
} else {
phase = 2;
currentI = 1;
currentJ = 0;
}
} else if (phase === 2) {
// Fill first column (s2 empty)
if (currentI <= m) {
dp[currentI][0] = dp[currentI - 1][0] && s1[currentI - 1] === s3[currentI - 1];
document.getElementById("status").textContent =
`dp[${currentI}][0]: s1[${currentI-1}]='${s1[currentI-1]}' vs s3[${currentI-1}]='${s3[currentI-1]}' → ${dp[currentI][0]}`;
currentI++;
} else {
phase = 3;
currentI = 1;
currentJ = 1;
}
} else if (phase === 3) {
// Fill rest of table
const k = currentI + currentJ - 1;
const curr = s3[k];
const matchS1 = dp[currentI - 1][currentJ] && s1[currentI - 1] === curr;
const matchS2 = dp[currentI][currentJ - 1] && s2[currentJ - 1] === curr;
dp[currentI][currentJ] = matchS1 || matchS2;
let explanation = `dp[${currentI}][${currentJ}]: s3[${k}]='${curr}' `;
if (matchS1) explanation += `← s1[${currentI-1}]='${s1[currentI-1]}' `;
if (matchS2) explanation += `← s2[${currentJ-1}]='${s2[currentJ-1]}' `;
explanation += `→ ${dp[currentI][currentJ]}`;
document.getElementById("status").textContent = explanation;
currentJ++;
if (currentJ > n) {
currentJ = 1;
currentI++;
if (currentI > m) {
phase = 4;
}
}
}
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";
step(); // Final status update
return;
}
step();
}, 600);
}
document.getElementById("autoRunBtn").addEventListener("click", autoRun);
document.getElementById("stepBtn").addEventListener("click", step);
document.getElementById("resetBtn").addEventListener("click", reset);
reset();
</script>
</body>
</html>