Alien Dictionary
Master this topic with zero to advance depth.
Alien Dictionary
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.
Visual Representation
Words: ["wrt","wrf","er","ett","rftt"]
Comparisons:
1. "wrt" vs "wrf" -> t comes before f (t -> f)
2. "wrf" vs "er" -> w comes before e (w -> e)
3. "er" vs "ett" -> r comes before t (r -> t)
4. "ett" vs "rftt" -> e comes before r (e -> r)
Graph: w -> e -> r -> t -> f
Result: "wertf"Examples
From the comparisons, the order is w < e < r < t < f.
Level II: Intermediate (Topological Sort / DFS)
Intuition
Alternatively, you can use DFS to perform a topological sort. For each character, we explore all its 'neighbors' and then add the character to a stack.
Thought Process
- Graph preparation is the same as Level III.
- Use a
statemap: 0 = unvisited, 1 = visiting (checking for cycles), 2 = visited. - In DFS(u):
- If state is 1, return cycle found.
- If state is 2, return OK.
- Set state to 1.
- DFS neighbors. If any fails, return false.
- Set state to 2 and prepend
uto result list.
Pattern: DFS Cycle Detection
Detailed Dry Run
["wrt","wrf","er"]
- t->f, w->e
- DFS(w): DFS(e), prepend e, prepend w. Order: we...
- DFS(r)... final order wertf.
Level III: Optimal (Topological Sort / Kahn's)
Intuition
The sorted list of words gives us relative ordering of characters. This is a classic Topological Sort problem. We extract dependencies from adjacent words and then apply Kahn's algorithm.
Thought Process
- Initialize a graph
adjandindegreemap for all unique characters. - Compare every two adjacent words
word1andword2:- Find the first non-matching character
c1inword1andc2inword2. - Add edge
c1 -> c2and incrementindegree[c2]. - Edge case: If
word2is a prefix ofword1(e.g., "abc", "ab"), return""(invalid).
- Find the first non-matching character
- Apply Kahn's Algorithm (standard BFS topological sort).
- If the resulting string length != number of unique characters, a cycle exists; return
"".
Pattern: Lexicographical Ordering / Kahn's
Detailed Dry Run
["wrt","wrf","er"]
- t -> f, w -> e
- Unique: {w,r,t,f,e}
- Indegrees: f:1, e:1, others:0
- Queue: [w, r, t]
- Pop w: Order "w", e's indegree -> 0, Queue [r, t, e]
- ... final order "wertf"
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.