Alien Dictionary
Pattern: Topological sort
Each pair of neighbouring words gives at most one rule: at the first position where they differ, the first word's letter comes before the second's. Build a graph of those rules on the first k letters and topologically sort it; a cycle, or a word placed before its own prefix, means no order exists.
The problem
Words of an alien language, using the first k letters, are given in sorted order. Return an order of all k letters
consistent with them, or "" if none exists. Several orders can be valid; this guide always takes the smallest-numbered letter that is ready, so the answer is unique.
Think first
- What does one pair of neighbouring words tell you?
- What if one word is a prefix of the word before it?
- How do you turn the rules into an order?
Hints
Brute force, and why it fails
Try every order of the k letters and check every pair of words: O(k! × total length).
The key insight
Only first differences carry information, so the rules form a small graph whose topological order is the answer.
Dry run
| rules | b<a d<a |
|---|
words baa, abcd, abca, cab, cad; k = 4. baa / abcd: b before a. abcd / abca: d before a.
The plan
for neighbouring words: first difference x, y -> edge x → y (or "" if a prefix comes second)
Kahn over k letters, smallest first
Complexity
- Time
O(total length + k log k)- Space
O(k + rules)
Each pair of words is compared once.
Edge cases
- One word: letters in alphabetical order.
- Conflicting rules: "".
- "ab" before "a": "".
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public String findOrder(String[] words, int k) {
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i < k; i++) adj.add(new ArrayList<>());
int[] indegree = new int[k];
for (int w = 0; w + 1 < words.length; w++) { // neighbouring words give at most one rule each
String a = words[w], b = words[w + 1];
int i = 0;
while (i < a.length() && i < b.length() && a.charAt(i) == b.charAt(i)) i++;
if (i < a.length() && i < b.length()) {
adj.get(a.charAt(i) - 'a').add(b.charAt(i) - 'a'); // the first difference: a's letter comes first
indegree[b.charAt(i) - 'a']++;
} else if (a.length() > b.length()) return ""; // a word before its own prefix: impossible
}
PriorityQueue<Integer> ready = new PriorityQueue<>(); // smallest letter first among those ready
for (int i = 0; i < k; i++) if (indegree[i] == 0) ready.add(i);
StringBuilder out = new StringBuilder();
while (!ready.isEmpty()) {
int u = ready.poll();
out.append((char) ('a' + u));
for (int v : adj.get(u)) if (--indegree[v] == 0) ready.add(v);
}
return out.length() == k ? out.toString() : ""; // a cycle of rules: no order
}
}C++
class Solution {
public:
string findOrder(vector<string>& words, int k) {
vector<vector<int>> adj(k);
vector<int> indegree(k, 0);
for (size_t w = 0; w + 1 < words.size(); w++) { // neighbouring words give at most one rule each
const string& a = words[w];
const string& b = words[w + 1];
size_t i = 0;
while (i < a.size() && i < b.size() && a[i] == b[i]) i++;
if (i < a.size() && i < b.size()) {
adj[a[i] - 'a'].push_back(b[i] - 'a'); // the first difference: a's letter comes first
indegree[b[i] - 'a']++;
} else if (a.size() > b.size()) return ""; // a word before its own prefix: impossible
}
priority_queue<int, vector<int>, greater<int>> ready; // smallest letter first among those ready
for (int i = 0; i < k; i++) if (indegree[i] == 0) ready.push(i);
string out;
while (!ready.empty()) {
int u = ready.top();
ready.pop();
out += static_cast<char>('a' + u);
for (int v : adj[u]) if (--indegree[v] == 0) ready.push(v);
}
return static_cast<int>(out.size()) == k ? out : ""; // a cycle of rules: no order
}
};Python
import heapq
class Solution:
def findOrder(self, words: list[str], k: int) -> str:
adj, indegree = [[] for _ in range(k)], [0] * k
for a, b in zip(words, words[1:]): # neighbouring words give at most one rule each
for x, y in zip(a, b):
if x != y:
adj[ord(x) - 97].append(ord(y) - 97) # the first difference: a's letter comes first
indegree[ord(y) - 97] += 1
break
else:
if len(a) > len(b):
return "" # a word before its own prefix: impossible
ready = [i for i in range(k) if indegree[i] == 0] # smallest letter first among those ready
heapq.heapify(ready)
out = []
while ready:
u = heapq.heappop(ready)
out.append(chr(97 + u))
for v in adj[u]:
indegree[v] -= 1
if indegree[v] == 0:
heapq.heappush(ready, v)
return "".join(out) if len(out) == k else "" # a cycle of rules: no orderCommon mistakes
- Comparing letters after the first difference.
- Leaving out letters that never appear in a rule.