Alien Dictionary Problem
Description
LeetCode Problem 269.
There is a new alien language that uses the English alphabet. However, the order of the letters is unknown to you.
You are given a list of strings words from the alien language's dictionary. Now it is claimed that the strings in words are sorted lexicographically by the rules of this new language.
If this claim is incorrect, and the given arrangement of string in words cannot correspond to any order of letters, return "".
Otherwise, 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 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 "".
Constraints:
1 <= words.length <= 1001 <= words[i].length <= 100words[i]consists of only lowercase English letters.
Solution
Approach: Build a Graph, Then Topological Sort
Comparing two adjacent words tells us about one pair of letters: at the first position where they differ, the letter in the first word comes before the letter in the second. Nothing after that position matters. For "wrt" and "wrf" we learn t before f; for "wrf" and "er" we learn w before e. Pairs that are not adjacent add nothing new, since sorting is transitive.
There is one special case: if two adjacent words have no differing position, the shorter one must come first. ["abc", "ab"] is impossible under any order, so return "" right away.
Each rule "a before b" is a directed edge a -> b. An alphabet that respects all the rules is a topological order of this graph, which we find with Kahn's algorithm:
- Every letter that appears in the words is a node, even if no rule mentions it.
- Put all letters with no incoming edges in a queue. Repeatedly take one out, append it to the result, and remove its outgoing edges; a letter whose last incoming edge is removed joins the queue.
- If some letters never reach the queue, they are on a cycle (like
z -> x -> zin["z","x","z"]), so no order exists: return"".
Add each edge only once, otherwise the in-degree counts would be off.
Complexity: O(C) time, where C is the total length of all words. The graph has at most 26 nodes and 26 × 26 edges, so the topological sort and the extra space are constant.
import collections
class Solution:
def alienOrder(self, words: List[str]) -> str:
letters = {c for w in words for c in w}
after = {c: set() for c in letters} # after[a]: letters that must come after a
indegree = {c: 0 for c in letters}
for w1, w2 in zip(words, words[1:]):
for a, b in zip(w1, w2):
if a != b:
# The first difference is the only thing this pair tells us.
if b not in after[a]:
after[a].add(b)
indegree[b] += 1
break
else:
if len(w1) > len(w2):
return "" # a word comes before its own prefix: no order works
# Kahn's algorithm: repeatedly output a letter nothing else has to precede.
queue = collections.deque(c for c in letters if indegree[c] == 0)
order = []
while queue:
a = queue.popleft()
order.append(a)
for b in after[a]:
indegree[b] -= 1
if indegree[b] == 0:
queue.append(b)
# Letters left over lie on a cycle.
return "".join(order) if len(order) == len(letters) else ""