|
| 1 | +/** |
| 2 | + * https://leetcode.com/problems/alien-dictionary |
| 3 | + * T.C. O(N * M) N: number of words, M: average length of word |
| 4 | + * S.C. O(1) 26 characters |
| 5 | + */ |
| 6 | +function alienOrder(words: string[]): string { |
| 7 | + const graph: Record<string, Set<string>> = {}; |
| 8 | + const inDegree: Record<string, number> = {}; |
| 9 | + |
| 10 | + // Initialize the graph |
| 11 | + for (const word of words) { |
| 12 | + for (const char of word) { |
| 13 | + if (!graph[char]) { |
| 14 | + graph[char] = new Set(); |
| 15 | + inDegree[char] = 0; |
| 16 | + } |
| 17 | + } |
| 18 | + } |
| 19 | + |
| 20 | + // Build the graph |
| 21 | + for (let i = 0; i < words.length - 1; i++) { |
| 22 | + const word1 = words[i]; |
| 23 | + const word2 = words[i + 1]; |
| 24 | + |
| 25 | + // Check invalid case: if word1 is longer and is prefix of word2 |
| 26 | + if (word1.length > word2.length && word1.startsWith(word2)) { |
| 27 | + return ''; |
| 28 | + } |
| 29 | + |
| 30 | + let j = 0; |
| 31 | + while (j < Math.min(word1.length, word2.length)) { |
| 32 | + if (word1[j] !== word2[j]) { |
| 33 | + const curSet = graph[word1[j]]; |
| 34 | + if (!curSet.has(word2[j])) { |
| 35 | + curSet.add(word2[j]); |
| 36 | + inDegree[word2[j]]++; |
| 37 | + } |
| 38 | + break; |
| 39 | + } |
| 40 | + j++; |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + // Topological sort |
| 45 | + const queue: string[] = []; |
| 46 | + for (const [char, degree] of Object.entries(inDegree)) { |
| 47 | + if (degree === 0) { |
| 48 | + queue.push(char); |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + const result: string[] = []; |
| 53 | + while (queue.length) { |
| 54 | + const char = queue.shift(); |
| 55 | + result.push(char!); |
| 56 | + for (const next of graph[char!]) { |
| 57 | + inDegree[next]--; |
| 58 | + if (inDegree[next] === 0) { |
| 59 | + queue.push(next); |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + return result.length === Object.keys(inDegree).length // |
| 65 | + ? result.join('') |
| 66 | + : ''; |
| 67 | +} |
0 commit comments