-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0091_decode_ways.html
More file actions
600 lines (500 loc) · 20.1 KB
/
0091_decode_ways.html
File metadata and controls
600 lines (500 loc) · 20.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>091 - Decode Ways</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">#091</span> Decode Ways</h1>
<p>
Given a string of digits, count the ways to decode it as letters (A=1, B=2, ..., Z=26).
Uses dynamic programming: dp[i] = dp[i-1] (single digit) + dp[i-2] (two digits if valid).
</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/0091_decode_ways/0091_decode_ways.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>Dynamic Programming <strong>breaks big problems into smaller ones</strong>:</p>
<ul>
<li><strong>Subproblems:</strong> Solve smaller versions first</li>
<li><strong>Memoization:</strong> Cache results to avoid recalculation</li>
<li><strong>Build up:</strong> Combine small solutions for final answer</li>
<li><strong>State:</strong> Define what each position represents</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 decode "226"</div>
<svg id="visualization"></svg>
</section>
<section class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import Dict
"""
LeetCode Decode Ways
Problem from LeetCode: https://leetcode.com/problems/decode-ways/
Description:
A message containing letters from A-Z can be encoded into numbers using the mapping:
'A' -> "1"
'B' -> "2"
...
'Z' -> "26"
To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into:
- "AAJF" with the grouping (1 1 10 6)
- "KJF" with the grouping (11 10 6)
Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06".
Given a string s containing only digits, return the number of ways to decode it.
Example 1:
Input: s = "12"
Output: 2
Explanation: "12" could be decoded as "AB" (1 2) or "L" (12).
Example 2:
Input: s = "226"
Output: 3
Explanation: "226" could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).
Example 3:
Input: s = "06"
Output: 0
Explanation: "06" cannot be mapped to "F" because of the leading zero ("6" is different from "06").
"""
class Solution:
def numDecodings(self, s: str) -> int:
"""
Calculate the number of ways to decode a string of digits.
Uses dynamic programming with constant space.
Args:
s: String containing only digits
Returns:
int: Number of ways to decode the string
"""
if not s or s[0] == '0':
return 0
# Initialize variables to track ways to decode
# prev2: ways to decode s[0:i-2]
# prev1: ways to decode s[0:i-1]
# current: ways to decode s[0:i]
prev2, prev1 = 1, 1
for i in range(1, len(s)):
current = 0
# Check if current digit is valid (not '0')
if s[i] != '0':
current += prev1
# Check if current and previous digits form a valid code (10-26)
# Get the value of the two-digit number
two_digit = int(s[i-1:i+1])
if 10 <= two_digit <= 26:
current += prev2
# Shift values for next iteration
prev2, prev1 = prev1, current
return prev1
def numDecodings_memo(self, s: str) -> int:
"""
Calculate the number of ways to decode a string using memoization.
Args:
s: String containing only digits
Returns:
int: Number of ways to decode the string
"""
# Memoization dictionary
memo = {}
def dp(index: int) -> int:
"""Recursive helper function with memoization."""
# Base case: reached the end of the string
if index == len(s):
return 1
# Base case: invalid leading zero
if s[index] == '0':
return 0
# Check if result is already memoized
if index in memo:
return memo[index]
# Decode current digit
ways = dp(index + 1)
# Decode two digits if possible
if index + 1 < len(s) and int(s[index:index+2]) <= 26:
ways += dp(index + 2)
# Memoize and return
memo[index] = ways
return ways
return dp(0)
def numDecodings_tabulation(self, s: str) -> int:
"""
Calculate the number of ways to decode a string using tabulation.
Args:
s: String containing only digits
Returns:
int: Number of ways to decode the string
"""
n = len(s)
# dp[i] represents the number of ways to decode s[0:i]
dp = [0] * (n + 1)
dp[0] = 1 # Base case: empty string has 1 way to decode
for i in range(1, n + 1):
# Single digit decode
if s[i-1] != '0':
dp[i] += dp[i-1]
# Two digit decode
if i > 1 and s[i-2] != '0' and int(s[i-2:i]) <= 26:
dp[i] += dp[i-2]
return dp[n]
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
s1 = "12"
result1 = solution.numDecodings(s1)
print(f"Example 1: s='{s1}', result={result1}") # Expected output: 2
# Example 2
s2 = "226"
result2 = solution.numDecodings(s2)
print(f"Example 2: s='{s2}', result={result2}") # Expected output: 3
# Example 3
s3 = "06"
result3 = solution.numDecodings(s3)
print(f"Example 3: s='{s3}', result={result3}") # Expected output: 0
# Additional example
s4 = "10"
result4 = solution.numDecodings(s4)
print(f"Example 4: s='{s4}', result={result4}") # Expected output: 1
# Compare with other approaches
print("\nUsing memoization approach:")
print(f"Example 1: {solution.numDecodings_memo(s1)}")
print(f"Example 2: {solution.numDecodings_memo(s2)}")
print("\nUsing tabulation approach:")
print(f"Example 1: {solution.numDecodings_tabulation(s1)}")
print(f"Example 2: {solution.numDecodings_tabulation(s2)}")
</pre>
</div>
</section>
</div>
<script>
const width = 900;
const height = 550;
const svg = d3.select("#visualization")
.attr("width", width)
.attr("height", height);
const s = "226";
let dp = [];
let currentIdx = 0;
let prev2 = 1;
let prev1 = 1;
let decodings = [];
let animationTimer = null;
// Mapping
const charMap = {};
for (let i = 1; i <= 26; i++) {
charMap[i] = String.fromCharCode(64 + i);
}
function reset() {
dp = [1]; // dp[0] = 1 for empty prefix
currentIdx = 0;
prev2 = 1;
prev1 = 1;
decodings = [];
// Calculate all decodings
calculateDecodings(s, 0, '');
if (animationTimer) clearInterval(animationTimer);
document.getElementById("status").textContent = `Decoding "${s}" - found ${decodings.length} possible decodings`;
render();
}
function calculateDecodings(str, idx, current) {
if (idx === str.length) {
decodings.push(current);
return;
}
// Single digit
if (str[idx] !== '0') {
const digit = parseInt(str[idx]);
calculateDecodings(str, idx + 1, current + charMap[digit]);
}
// Two digits
if (idx + 1 < str.length) {
const twoDigit = parseInt(str.substring(idx, idx + 2));
if (twoDigit >= 10 && twoDigit <= 26) {
calculateDecodings(str, idx + 2, current + charMap[twoDigit]);
}
}
}
function render() {
svg.selectAll("*").remove();
// Draw input string
drawInput();
// Draw DP table
drawDPTable();
// Draw character mapping
drawMapping();
// Draw possible decodings
drawDecodings();
}
function drawInput() {
svg.append("text")
.attr("x", 30)
.attr("y", 40)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("Input String:");
s.split('').forEach((ch, idx) => {
const x = 140 + idx * 50;
const isProcessed = idx < currentIdx;
const isCurrent = idx === currentIdx;
svg.append("rect")
.attr("x", x)
.attr("y", 20)
.attr("width", 45)
.attr("height", 45)
.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 + 22)
.attr("y", 50)
.attr("text-anchor", "middle")
.attr("font-size", "20px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text(ch);
// Index label
svg.append("text")
.attr("x", x + 22)
.attr("y", 80)
.attr("text-anchor", "middle")
.attr("font-size", "11px")
.attr("fill", "#64748b")
.text(`i=${idx}`);
});
}
function drawDPTable() {
const startX = 30;
const startY = 130;
svg.append("text")
.attr("x", startX)
.attr("y", startY)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("DP Values (ways to decode s[0:i]):");
// Draw dp values
for (let i = 0; i <= s.length; i++) {
const x = startX + i * 70;
const y = startY + 25;
const value = i < dp.length ? dp[i] : "?";
const isCalculated = i < dp.length;
svg.append("rect")
.attr("x", x)
.attr("y", y)
.attr("width", 60)
.attr("height", 40)
.attr("rx", 6)
.attr("fill", isCalculated ? "#dbeafe" : "#f8fafc")
.attr("stroke", isCalculated ? "#3b82f6" : "#94a3b8")
.attr("stroke-width", 2);
svg.append("text")
.attr("x", x + 30)
.attr("y", y - 5)
.attr("text-anchor", "middle")
.attr("font-size", "11px")
.attr("fill", "#64748b")
.text(`dp[${i}]`);
svg.append("text")
.attr("x", x + 30)
.attr("y", y + 28)
.attr("text-anchor", "middle")
.attr("font-size", "18px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text(value);
}
// Formula explanation
svg.append("text")
.attr("x", startX)
.attr("y", startY + 100)
.attr("font-size", "12px")
.attr("fill", "#64748b")
.text("Formula: dp[i] = dp[i-1] (if s[i-1] valid) + dp[i-2] (if s[i-2:i] in 10-26)");
}
function drawMapping() {
const startX = 30;
const startY = 260;
svg.append("text")
.attr("x", startX)
.attr("y", startY)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("Character Mapping:");
// Show relevant mappings
const relevantMappings = [1, 2, 6, 22, 26];
relevantMappings.forEach((num, idx) => {
const x = startX + idx * 80;
svg.append("rect")
.attr("x", x)
.attr("y", startY + 15)
.attr("width", 70)
.attr("height", 30)
.attr("rx", 5)
.attr("fill", "#e0e7ff")
.attr("stroke", "#6366f1")
.attr("stroke-width", 1);
svg.append("text")
.attr("x", x + 35)
.attr("y", startY + 36)
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.attr("fill", "#1e293b")
.text(`${num} → ${charMap[num]}`);
});
}
function drawDecodings() {
const startX = 30;
const startY = 340;
svg.append("text")
.attr("x", startX)
.attr("y", startY)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text(`Possible Decodings (${decodings.length} ways):`);
decodings.forEach((decoding, idx) => {
const x = startX + (idx % 4) * 150;
const y = startY + 25 + Math.floor(idx / 4) * 45;
// Show the decoding with its grouping
let grouping = getGrouping(decoding);
svg.append("rect")
.attr("x", x)
.attr("y", y)
.attr("width", 140)
.attr("height", 35)
.attr("rx", 6)
.attr("fill", "#d1fae5")
.attr("stroke", "#10b981")
.attr("stroke-width", 2);
svg.append("text")
.attr("x", x + 70)
.attr("y", y + 15)
.attr("text-anchor", "middle")
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text(decoding);
svg.append("text")
.attr("x", x + 70)
.attr("y", y + 28)
.attr("text-anchor", "middle")
.attr("font-size", "10px")
.attr("fill", "#64748b")
.text(grouping);
});
// Time/Space complexity
svg.append("text")
.attr("x", startX)
.attr("y", 500)
.attr("font-size", "12px")
.attr("fill", "#64748b")
.text("Time: O(n), Space: O(1) using two variables instead of array");
}
function getGrouping(decoding) {
// Reconstruct the grouping from the decoding
let result = [];
let remaining = s;
for (const char of decoding) {
const code = char.charCodeAt(0) - 64;
const codeStr = code.toString();
if (remaining.startsWith(codeStr)) {
result.push(codeStr);
remaining = remaining.substring(codeStr.length);
}
}
return `(${result.join(' ')})`;
}
function step() {
if (currentIdx >= s.length) {
document.getElementById("status").textContent =
`✓ Complete! "${s}" has ${dp[dp.length - 1]} decoding ways`;
return;
}
if (currentIdx === 0) {
// First character
if (s[0] === '0') {
dp.push(0);
document.getElementById("status").textContent =
`s[0]='0' is invalid. dp[1] = 0`;
} else {
dp.push(1);
document.getElementById("status").textContent =
`s[0]='${s[0]}' → '${charMap[parseInt(s[0])]}'. dp[1] = 1`;
}
currentIdx++;
} else {
let current = 0;
let explanation = [];
// Single digit
if (s[currentIdx] !== '0') {
current += dp[currentIdx];
explanation.push(`single '${s[currentIdx]}' → ${charMap[parseInt(s[currentIdx])]}: +dp[${currentIdx}]=${dp[currentIdx]}`);
}
// Two digits
const twoDigit = parseInt(s.substring(currentIdx - 1, currentIdx + 1));
if (twoDigit >= 10 && twoDigit <= 26) {
current += dp[currentIdx - 1];
explanation.push(`pair '${s.substring(currentIdx - 1, currentIdx + 1)}' → ${charMap[twoDigit]}: +dp[${currentIdx - 1}]=${dp[currentIdx - 1]}`);
}
dp.push(current);
document.getElementById("status").textContent =
`dp[${currentIdx + 1}] = ${current}. ${explanation.join(', ')}`;
currentIdx++;
}
render();
}
function autoRun() {
if (animationTimer) {
clearInterval(animationTimer);
animationTimer = null;
document.getElementById("autoRunBtn").textContent = "▶ Auto Run";
return;
}
document.getElementById("autoRunBtn").textContent = "⏸ Pause";
animationTimer = setInterval(() => {
if (currentIdx >= s.length) {
clearInterval(animationTimer);
animationTimer = null;
document.getElementById("autoRunBtn").textContent = "▶ Auto Run";
return;
}
step();
}, 1200);
}
document.getElementById("autoRunBtn").addEventListener("click", autoRun);
document.getElementById("stepBtn").addEventListener("click", step);
document.getElementById("resetBtn").addEventListener("click", reset);
reset();
</script>
</body>
</html>