Alien Dictionary

Determine the alien character order from a list of sorted alien words — topological sort over derived precedence.

Hard
Time O(C) Space O(|Σ|)
LeetCode
6 min read
topological-sort graph

Problem#

Given words sorted according to some unknown alphabet, return a valid character ordering. Return "" if no valid order exists.

Examples#

  • ["wrt","wrf","er","ett","rftt"]"wertf"

Constraints#

  • 1 <= words.length <= 100.

Hints#

Hint 1
From every adjacent pair, the first differing character pair gives a precedence edge. Build the graph, then Kahn’s BFS.

Approach#

  1. Collect every unique character. 2. For each adjacent word pair, find the first differing char pair and add an edge (prev → curr). Catch the “prefix-after-longer-word” invalid case (e.g., ["abc", "ab"]). 3. Kahn’s BFS topological sort. If not all characters end up in the output, return "" (cycle).

Solution#

Alien Dictionary
class Solution {
public:
string alienOrder(vector<string>& words) {
unordered_map<char, unordered_set<char>> adj;
unordered_map<char, int> indeg;
for (auto& w : words) for (char c : w) indeg[c];
for (int i = 0; i + 1 < (int)words.size(); ++i) {
const string& a = words[i];
const string& b = words[i + 1];
if (a.size() > b.size() && a.substr(0, b.size()) == b) return "";
for (int j = 0; j < (int)min(a.size(), b.size()); ++j) {
if (a[j] != b[j]) {
if (adj[a[j]].insert(b[j]).second) ++indeg[b[j]];
break;
}
}
}
queue<char> q;
for (auto& [c, d] : indeg) if (d == 0) q.push(c);
string out;
while (!q.empty()) {
char c = q.front(); q.pop();
out += c;
for (char nb : adj[c]) {
if (--indeg[nb] == 0) q.push(nb);
}
}
return (int)out.size() == (int)indeg.size() ? out : "";
}
};

Editorial#

Three failure modes: a long word that’s a prefix of a shorter word, a cycle in the derived precedence graph, and ambiguous orderings (multiple valid answers — any one is accepted). The insert.second check avoids inflating in-degree on duplicate edges.

Complexity#

  • Time: O(C) where C is total character count.
  • Space: O(|Σ|).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.