You are given a sorted dictionary (a list of words) of an alien language. In this language, the ordering among letters is unknown. You need to determine the order of the letters in the alien language based on the given dictionary. The dictionary is sorted lexicographically according to the rules of the alien language.
For example:
Given the following words:
[
"wrt",
"wrf",
"er",
"ett",
"rftt"
]
The correct order is "wertf".
Another example:
[
"z",
"x"
]
The correct order is "zx".
Constraints:
Write a function alienOrder(words)
that takes a list of strings words
as input and returns a string representing the order of the letters in the alien language. If no valid order exists, return an empty string.
Let's tackle the "Alien Dictionary" problem. We're given a list of words from an alien language, and our goal is to deduce the order of the letters in this language. A naive approach would involve comparing all pairs of words to find letter orderings, but this can be quite inefficient.
This approach is inefficient because it involves redundant comparisons and can have a high time complexity.
A more efficient solution involves using a graph and topological sorting. This approach focuses on extracting character orderings directly from adjacent words in the input list and utilizes topological sorting to create the final alphabet order.
words = ["wrt", "wrf", "er", "ett", "rftt"]
, comparing "wrt" and "wrf" tells us 't' comes before 'f'.Here's the Python code:
from collections import defaultdict, deque
def alienOrder(words):
graph = defaultdict(list)
in_degree = {}
unique_chars = set()
for word in words:
for char in word:
in_degree[char] = 0
unique_chars.add(char)
for i in range(len(words) - 1):
word1, word2 = words[i], words[i+1]
min_len = min(len(word1), len(word2))
for j in range(min_len):
if word1[j] != word2[j]:
if word2[j] not in graph[word1[j]]:
graph[word1[j]].append(word2[j])
in_degree[word2[j]] += 1
break
else:
if len(word1) > len(word2):
return "" # Invalid order
queue = deque([char for char in in_degree if in_degree[char] == 0])
result = []
while queue:
char = queue.popleft()
result.append(char)
for neighbor in graph[char]:
in_degree[neighbor] -= 1
if in_degree[neighbor] == 0:
queue.append(neighbor)
if len(result) != len(unique_chars):
return "" # Cycle detected
return "".join(result)