Alien Dictionary (LeetCode 269): Solution and Explanation
You receive a list of words that is sorted according to an unknown alphabet built from English letters. Work out one possible ordering of the letters that is consistent with the list, or return an empty string if no valid ordering exists.
Watch it run step by step
Try your own input and write the code →Intuition
The only information about letter order comes from comparing neighbors in the sorted list. When two adjacent words first differ at some position, the letter in the earlier word must come before the letter in the later word. Everything after that first difference tells you nothing, and comparing non-adjacent words adds no new facts because sortedness is transitive.
Each of those facts is an edge in a directed graph over letters: a before b becomes an edge from a to b. A valid alphabet is then exactly a topological ordering of this graph. If the graph has a cycle, such as a before b and b before a, no ordering is possible. Letters that never take part in any comparison still need to appear in the answer, so every letter in every word must be a node.
There is one more way the input can be invalid. If a word is followed by its own proper prefix, like abc before ab, no alphabet can make that sorted, because a prefix always comes first. You check that case while building edges.
For the ordering itself, DFS with three states works well. A letter is either unvisited, on the current DFS path, or finished. Reaching a letter that is on the current path means a cycle. Appending each letter after all its successors are finished produces a reverse topological order, which you flip at the end.
Approach: Graph building plus DFS topological sort
- Create an adjacency set for every letter that appears in any word.
- For each adjacent pair of words, if the first is longer and the shorter is its prefix, return an empty string.
- Otherwise find the first index where they differ and add an edge from the first word's letter to the second's, then stop scanning that pair.
- Run DFS from every letter, marking it
Truewhile it is on the current path andFalseonce finished. - If DFS reaches a letter marked
True, a cycle exists, so return an empty string. - Append each letter after its neighbors finish, then reverse the result and join it into the answer.
Step-by-step example
words = ["wrt", "wrf", "er", "ett", "rftt"]
- The letters are w, r, t, f and e. Comparing wrt and wrf gives t before f.
- Comparing wrf and er gives w before e. Comparing er and ett gives r before t. Comparing ett and rftt gives e before r.
- DFS from w goes to e, then r, then t, then f. The letter f has no outgoing edges, so it is appended first, followed by t, r, e and w as the calls unwind.
- The post-order list is f, t, r, e, w, and all letters are now finished, so the remaining DFS calls return immediately.
- Reversing gives
wertf, which satisfies every edge.
Code: Python, Java, C++
1class Solution:
2 def alienOrder(self, words: List[str]) -> str:
3 adj = {c:set() for w in words for c in w}
4
5 for i in range(len(words) - 1):
6 w1, w2 = words[i], words[i + 1]
7 minLen = min(len(w1), len(w2))
8 if len(w1) > len(w2) and w1[:minLen] == w2[:minLen]:
9 return ""
10 for j in range(minLen):
11 if w1[j] != w2[j]:
12 adj[w1[j]].add(w2[j])
13 break
14
15 visited = {} # False=visited, True=current path
16 res = []
17
18 def dfs(c):
19 if c in visited:
20 return visited[c]
21
22 visited[c] = True
23 for nei in adj[c]:
24 if dfs(nei): return True
25 visited[c] = False
26 res.append(c)
27
28 for c in adj:
29 if dfs(c): return ""
30 res.reverse()
31 return "".join(res)1class Solution {
2 public String alienOrder(String[] words) {
3 Map<Character, Set<Character>> adj = new HashMap<>();
4 for (String w : words) for (char c : w.toCharArray()) adj.putIfAbsent(c, new HashSet<>());
5
6 for (int i = 0; i < words.length - 1; i++) {
7 String w1 = words[i], w2 = words[i+1];
8 int minLen = Math.min(w1.length(), w2.length());
9 if (w1.length() > w2.length() && w1.startsWith(w2)) return "";
10 for (int j = 0; j < minLen; j++) {
11 if (w1.charAt(j) != w2.charAt(j)) {
12 adj.get(w1.charAt(j)).add(w2.charAt(j));
13 break;
14 }
15 }
16 }
17
18 Map<Character, Boolean> visit = new HashMap<>();
19 StringBuilder res = new StringBuilder();
20
21 for (Character c : adj.keySet()) {
22 if (dfs(c, adj, visit, res)) return "";
23 }
24 return res.reverse().toString();
25 }
26
27 private boolean dfs(Character c, Map<Character, Set<Character>> adj, Map<Character, Boolean> visit, StringBuilder res) {
28 if (visit.containsKey(c)) return visit.get(c);
29
30 visit.put(c, true);
31 for (Character nei : adj.get(c)) {
32 if (dfs(nei, adj, visit, res)) return true;
33 }
34 visit.put(c, false);
35 res.append(c);
36 return false;
37 }
38}1class Solution {
2public:
3 string alienOrder(vector<string>& words) {
4 unordered_map<char, unordered_set<char>> adj;
5 for (auto& w : words) for (char c : w) adj[c];
6
7 for (int i = 0; i < words.size() - 1; i++) {
8 string w1 = words[i], w2 = words[i + 1];
9 int minLen = min(w1.size(), w2.size());
10 if (w1.size() > w2.size() && w1.substr(0, minLen) == w2.substr(0, minLen)) return "";
11 for (int j = 0; j < minLen; j++) {
12 if (w1[j] != w2[j]) {
13 adj[w1[j]].insert(w2[j]);
14 break;
15 }
16 }
17 }
18
19 unordered_map<char, bool> visit;
20 string res = "";
21
22 function<bool(char)> dfs = [&](char c) {
23 if (visit.count(c)) return visit[c];
24
25 visit[c] = true;
26 for (char nei : adj[c]) {
27 if (dfs(nei)) return true;
28 }
29 visit[c] = false;
30 res += c;
31 return false;
32 };
33
34 for (auto& [c, _] : adj) {
35 if (dfs(c)) return "";
36 }
37 reverse(res.begin(), res.end());
38 return res;
39 }
40};Time and space complexity
O(C)
Building the graph compares adjacent words character by character, which is bounded by C, the total number of characters across all words. The DFS touches at most 26 letters and their edges.
O(U + E)
The adjacency sets and visit map hold U unique letters and E edges, which is bounded by 26 letters and a few hundred edges, so it is effectively constant.
Other approaches
Kahn's algorithm (BFS topological sort) (time O(C), space O(U + E))
Count in-degrees, start a queue with every letter of in-degree 0 and repeatedly remove letters, lowering their neighbors' in-degrees. If not every letter is output, there is a cycle. Many people find this cycle check easier to explain.
Compare all pairs of words (time O(n² × L), space O(U + E))
Deriving edges from every pair instead of adjacent pairs adds redundant edges and costs O(n² × L) time without improving correctness.
Common mistakes
- Comparing beyond the first differing character adds false edges; you must break after the first mismatch.
- Missing the prefix rule, so an input like ["abc", "ab"] returns an ordering instead of an empty string.
- Only creating nodes for letters that appear in edges drops letters that are unconstrained but still belong in the output.
- Using a single visited flag without distinguishing on path from finished either misses cycles or reports false ones.
Frequently asked questions
How do you detect an invalid alien dictionary?
There are two cases. A word followed by its own proper prefix is invalid, and a cycle in the letter graph is invalid. Either one means you return an empty string.
Why only compare adjacent words?
Sorted order is transitive, so the constraints from non-adjacent pairs are implied by the adjacent ones. Adjacent comparisons alone give every edge you need.
BFS or DFS for alien dictionary?
Both work. Kahn's BFS algorithm detects cycles by checking whether all letters were output, while DFS detects them by finding a back edge to a letter on the current path.
Is the answer unique?
Not always. Letters with no constraint between them can appear in any relative order, and any valid topological order is accepted.