-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0269_alien_dictionary.html
More file actions
662 lines (558 loc) · 23.2 KB
/
0269_alien_dictionary.html
File metadata and controls
662 lines (558 loc) · 23.2 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
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>269 - Alien Dictionary</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">#269</span> Alien Dictionary</h1>
<p>
Given a sorted list of words in an alien language, determine the character order.
Build a directed graph from character precedence, then use topological sort.
</p>
<div class="problem-meta">
<span class="meta-tag">🔗 Graph</span>
<span class="meta-tag">⏱️ O(n)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0269_alien_dictionary/0269_alien_dictionary.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>Graph problems are like <strong>exploring a maze</strong>:</p>
<ul>
<li><strong>Nodes:</strong> Points or locations</li>
<li><strong>Edges:</strong> Connections between nodes</li>
<li><strong>Traverse:</strong> Use DFS or BFS to explore</li>
<li><strong>Track visited:</strong> Avoid infinite loops</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 determine alien character order</div>
<svg id="visualization"></svg>
</section>
<section class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List, Dict
from collections import defaultdict
"""
LeetCode 269. Alien Dictionary
Problem from LeetCode: https://leetcode.com/problems/alien-dictionary/
Description:
There is a new alien language that uses the English alphabet. However, the order among the letters is unknown to you.
You are given a list of strings words from the alien language's dictionary, where the strings in words are sorted lexicographically by the rules of this new language.
Return a string of the unique letters in the new alien language sorted in lexicographically increasing order by the new language's rules. If there is no solution, return "". If there are multiple solutions, return any of them.
Example 1:
Input: words = ["wrt","wrf","er","ett","rftt"]
Output: "wertf"
Example 2:
Input: words = ["z","x"]
Output: "zx"
Example 3:
Input: words = ["z","x","z"]
Output: ""
Explanation: The order is invalid, so return "".
"""
class Solution:
def alien_order(self, words: List[str]) ->str:
"""
Determine the order of characters in an alien alphabet given a list of sorted words.
Args:
words: List of strings sorted by the rules of the alien language
Returns:
str: The order of characters in the alien language, or "" if no valid order exists
"""
reversed_list = defaultdict(list)
seen = {}
result = []
# Initialize the adjacency list with all characters
for word in words:
for c in word:
if c not in reversed_list:
reversed_list[c] = []
# Build the graph
for i in range(len(words) - 1):
word1 = words[i]
word2 = words[i + 1]
# Check for invalid order: if word1 is a prefix of word2, it should come before
if len(word1) > len(word2) and word1.startswith(word2):
return ''
# Find the first differing character
for j in range(min(len(word1), len(word2))):
if word1[j] != word2[j]:
reversed_list[word2[j]].append(word1[j])
break
# DFS to check for cycles and build the result
def dfs(c):
if c in seen:
return seen[c]
seen[c] = False # Mark as visiting (potential cycle)
for next_char in reversed_list[c]:
if not dfs(next_char):
return False
seen[c] = True # Mark as visited
result.append(c)
return True
# Process all characters
for c in reversed_list:
if c not in seen:
if not dfs(c):
return ''
# Check if all characters were included
if len(result) < len(reversed_list):
return ''
return ''.join(result)
def alien_order_b_f_s(self, words: List[str]) ->str:
"""
Implement the alien dictionary problem using BFS topological sort.
Args:
words: List of strings sorted by the rules of the alien language
Returns:
str: The order of characters in the alien language, or "" if no valid order exists
"""
from collections import deque
# Initialize the graph and in-degree counts
graph = defaultdict(set)
in_degree = {}
# Add all characters to the in_degree dictionary
for word in words:
for c in word:
in_degree[c] = 0
# Build the graph
for i in range(len(words) - 1):
word1 = words[i]
word2 = words[i + 1]
# Check for invalid order
if len(word1) > len(word2) and word1.startswith(word2):
return ''
# Find the first differing character
for j in range(min(len(word1), len(word2))):
if word1[j] != word2[j]:
# Add directed edge: word1[j] -> word2[j]
if word2[j] not in graph[word1[j]]:
graph[word1[j]].add(word2[j])
in_degree[word2[j]] += 1
break
# Start with characters that have no prerequisites
queue = deque([c for c in in_degree if in_degree[c] == 0])
result = []
# Process the queue
while queue:
curr = queue.popleft()
result.append(curr)
for next_char in graph[curr]:
in_degree[next_char] -= 1
if in_degree[next_char] == 0:
queue.append(next_char)
# Check if all characters were included
if len(result) != len(in_degree):
return ''
return ''.join(result)
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
words1 = ["wrt", "wrf", "er", "ett", "rftt"]
result1 = solution.alien_order(words1)
print(f"Example 1: {result1}") # Expected output: "wertf"
# Example 2
words2 = ["z", "x"]
result2 = solution.alien_order(words2)
print(f"Example 2: {result2}") # Expected output: "zx"
# Example 3
words3 = ["z", "x", "z"]
result3 = solution.alien_order(words3)
print(f"Example 3: {result3}") # Expected output: ""
# Try BFS approach
print("\nUsing BFS approach:")
result1_bfs = solution.alien_order_b_f_s(words1)
print(f"Example 1: {result1_bfs}")
result2_bfs = solution.alien_order_b_f_s(words2)
print(f"Example 2: {result2_bfs}")
result3_bfs = solution.alien_order_b_f_s(words3)
print(f"Example 3: {result3_bfs}")
</pre>
</div>
</section>
</div>
<script>
const width = 900;
const height = 650;
const svg = d3.select("#visualization")
.attr("width", width)
.attr("height", height);
// Example words
const words = ["wrt", "wrf", "er", "ett", "rftt"];
let graph = {};
let inDegree = {};
let queue = [];
let result = [];
let currentComparison = null;
let highlightEdge = null;
let animationTimer = null;
let steps = [];
let stepIdx = 0;
let phase = "build"; // "build" or "sort"
function reset() {
graph = {};
inDegree = {};
queue = [];
result = [];
currentComparison = null;
highlightEdge = null;
phase = "build";
steps = [];
stepIdx = 0;
// Initialize in-degree for all characters
for (const word of words) {
for (const c of word) {
if (!(c in inDegree)) {
inDegree[c] = 0;
graph[c] = new Set();
}
}
}
// Generate steps
generateSteps();
if (animationTimer) clearInterval(animationTimer);
document.getElementById("status").textContent = "Click Auto Run to determine alien character order";
render();
}
function generateSteps() {
// Build graph steps
for (let i = 0; i < words.length - 1; i++) {
const w1 = words[i];
const w2 = words[i + 1];
steps.push({ type: "compare", w1, w2, idx1: i, idx2: i + 1 });
for (let j = 0; j < Math.min(w1.length, w2.length); j++) {
if (w1[j] !== w2[j]) {
steps.push({ type: "edge", from: w1[j], to: w2[j], w1, w2, pos: j });
break;
}
}
}
// Topological sort steps
steps.push({ type: "start_sort" });
}
function render() {
svg.selectAll("*").remove();
// Draw words list
drawWords();
// Draw graph
drawGraph();
// Draw result
drawResult();
// Draw in-degree table
drawInDegree();
}
function drawWords() {
svg.append("text")
.attr("x", 50)
.attr("y", 40)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("Sorted Words (Alien Dictionary):");
words.forEach((word, idx) => {
const isActive = currentComparison &&
(idx === currentComparison[0] || idx === currentComparison[1]);
svg.append("rect")
.attr("x", 50 + idx * 90)
.attr("y", 55)
.attr("width", 80)
.attr("height", 35)
.attr("rx", 4)
.attr("fill", isActive ? "#fef3c7" : "#f8fafc")
.attr("stroke", isActive ? "#f59e0b" : "#94a3b8");
svg.append("text")
.attr("x", 50 + idx * 90 + 40)
.attr("y", 78)
.attr("text-anchor", "middle")
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text(word);
svg.append("text")
.attr("x", 50 + idx * 90 + 40)
.attr("y", 105)
.attr("text-anchor", "middle")
.attr("font-size", "10px")
.attr("fill", "#64748b")
.text(`[${idx}]`);
});
}
function drawGraph() {
const chars = Object.keys(inDegree);
const charPositions = {};
const centerX = 350;
const centerY = 320;
const radius = 120;
// Position characters in a circle
chars.forEach((c, idx) => {
const angle = (idx / chars.length) * 2 * Math.PI - Math.PI / 2;
charPositions[c] = {
x: centerX + radius * Math.cos(angle),
y: centerY + radius * Math.sin(angle)
};
});
svg.append("text")
.attr("x", centerX)
.attr("y", 150)
.attr("text-anchor", "middle")
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("Character Precedence Graph");
// Arrow marker
svg.append("defs").append("marker")
.attr("id", "arrowhead")
.attr("viewBox", "0 0 10 10")
.attr("refX", 28)
.attr("refY", 5)
.attr("markerWidth", 5)
.attr("markerHeight", 5)
.attr("orient", "auto")
.append("path")
.attr("d", "M 0 0 L 10 5 L 0 10 z")
.attr("fill", "#3b82f6");
svg.append("defs").append("marker")
.attr("id", "arrowhead-highlight")
.attr("viewBox", "0 0 10 10")
.attr("refX", 28)
.attr("refY", 5)
.attr("markerWidth", 5)
.attr("markerHeight", 5)
.attr("orient", "auto")
.append("path")
.attr("d", "M 0 0 L 10 5 L 0 10 z")
.attr("fill", "#f59e0b");
// Draw edges
for (const from in graph) {
for (const to of graph[from]) {
if (charPositions[from] && charPositions[to]) {
const isHighlight = highlightEdge &&
highlightEdge[0] === from && highlightEdge[1] === to;
const x1 = charPositions[from].x;
const y1 = charPositions[from].y;
const x2 = charPositions[to].x;
const y2 = charPositions[to].y;
// Calculate control point for curve
const dx = x2 - x1;
const dy = y2 - y1;
const cx = (x1 + x2) / 2 - dy * 0.2;
const cy = (y1 + y2) / 2 + dx * 0.2;
svg.append("path")
.attr("d", `M ${x1} ${y1} Q ${cx} ${cy} ${x2} ${y2}`)
.attr("fill", "none")
.attr("stroke", isHighlight ? "#f59e0b" : "#3b82f6")
.attr("stroke-width", isHighlight ? 3 : 2)
.attr("marker-end", isHighlight ? "url(#arrowhead-highlight)" : "url(#arrowhead)");
}
}
}
// Draw nodes
chars.forEach(c => {
const pos = charPositions[c];
const isInResult = result.includes(c);
const isInQueue = queue.includes(c);
svg.append("circle")
.attr("cx", pos.x)
.attr("cy", pos.y)
.attr("r", 22)
.attr("fill", () => {
if (isInResult) return "#d1fae5";
if (isInQueue) return "#fef3c7";
return "#dbeafe";
})
.attr("stroke", () => {
if (isInResult) return "#10b981";
if (isInQueue) return "#f59e0b";
return "#3b82f6";
})
.attr("stroke-width", 2);
svg.append("text")
.attr("x", pos.x)
.attr("y", pos.y + 6)
.attr("text-anchor", "middle")
.attr("font-size", "18px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text(c);
});
}
function drawInDegree() {
const x = 580;
const y = 180;
svg.append("text")
.attr("x", x)
.attr("y", y - 10)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("In-Degree:");
Object.entries(inDegree).forEach(([c, deg], idx) => {
svg.append("rect")
.attr("x", x + (idx % 3) * 90)
.attr("y", y + Math.floor(idx / 3) * 35)
.attr("width", 80)
.attr("height", 28)
.attr("rx", 4)
.attr("fill", deg === 0 ? "#d1fae5" : "#f8fafc")
.attr("stroke", deg === 0 ? "#10b981" : "#94a3b8");
svg.append("text")
.attr("x", x + (idx % 3) * 90 + 40)
.attr("y", y + Math.floor(idx / 3) * 35 + 18)
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text(`${c}: ${deg}`);
});
// Queue
svg.append("text")
.attr("x", x)
.attr("y", y + 100)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("Queue:");
svg.append("text")
.attr("x", x)
.attr("y", y + 125)
.attr("font-size", "14px")
.attr("fill", queue.length > 0 ? "#1e293b" : "#64748b")
.text(queue.length > 0 ? `[${queue.join(", ")}]` : "(empty)");
}
function drawResult() {
const y = 520;
svg.append("text")
.attr("x", 50)
.attr("y", y)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("Result (Topological Order):");
if (result.length === 0) {
svg.append("text")
.attr("x", 50)
.attr("y", y + 30)
.attr("font-size", "14px")
.attr("fill", "#64748b")
.text("(building graph...)");
} else {
result.forEach((c, idx) => {
svg.append("rect")
.attr("x", 50 + idx * 50)
.attr("y", y + 15)
.attr("width", 40)
.attr("height", 35)
.attr("rx", 4)
.attr("fill", "#d1fae5")
.attr("stroke", "#10b981");
svg.append("text")
.attr("x", 50 + idx * 50 + 20)
.attr("y", y + 38)
.attr("text-anchor", "middle")
.attr("font-size", "16px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text(c);
});
if (result.length === Object.keys(inDegree).length) {
svg.append("text")
.attr("x", 50)
.attr("y", y + 70)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#10b981")
.text(`✓ Alien alphabet: "${result.join("")}"`);
}
}
}
function step() {
if (stepIdx >= steps.length) {
// Do topological sort
if (queue.length > 0) {
const c = queue.shift();
result.push(c);
for (const next of graph[c]) {
inDegree[next]--;
if (inDegree[next] === 0) {
queue.push(next);
}
}
document.getElementById("status").textContent =
`Pop '${c}' from queue, add to result. Update neighbors.`;
} else if (result.length === Object.keys(inDegree).length) {
document.getElementById("status").textContent =
`✓ Complete! Alien alphabet: "${result.join("")}"`;
}
render();
return;
}
const s = steps[stepIdx++];
switch (s.type) {
case "compare":
currentComparison = [s.idx1, s.idx2];
highlightEdge = null;
document.getElementById("status").textContent =
`Comparing "${s.w1}" and "${s.w2}"`;
break;
case "edge":
if (!graph[s.from].has(s.to)) {
graph[s.from].add(s.to);
inDegree[s.to]++;
}
highlightEdge = [s.from, s.to];
document.getElementById("status").textContent =
`Found: '${s.from}' < '${s.to}' (first difference at position ${s.pos})`;
break;
case "start_sort":
phase = "sort";
currentComparison = null;
highlightEdge = null;
queue = Object.keys(inDegree).filter(c => inDegree[c] === 0);
document.getElementById("status").textContent =
`Graph complete! Starting topological sort. Queue: [${queue.join(", ")}]`;
break;
}
render();
}
function autoRun() {
if (animationTimer) {
clearInterval(animationTimer);
animationTimer = null;
document.getElementById("autoRunBtn").textContent = "▶ Auto Run";
return;
}
document.getElementById("autoRunBtn").textContent = "⏸ Pause";
animationTimer = setInterval(() => {
if (stepIdx >= steps.length && queue.length === 0) {
clearInterval(animationTimer);
animationTimer = null;
document.getElementById("autoRunBtn").textContent = "▶ Auto Run";
return;
}
step();
}, 800);
}
document.getElementById("autoRunBtn").addEventListener("click", autoRun);
document.getElementById("stepBtn").addEventListener("click", step);
document.getElementById("resetBtn").addEventListener("click", reset);
reset();
</script>
</body>
</html>