Alien Dictionary
Hard · Graphs
On LeetCode, Alien Dictionary needs LeetCode Premium (checked October 2026). Here it is free: run and submit in Python, JavaScript, Java or C++ with a free account.
Jump to codeGiven nonempty words sorted under an unknown character order, return any ordering of all observed characters consistent with that sort. Return an empty string if no valid ordering exists.
Examples
Example 1
words = ["wrt","wrf","er","ett","rftt"]
Output: "wertf"
Example 2
words = ["z","x"]
Output: "zx"
Constraints
- The input words will contain characters only from lowercase 'a' to 'z'.
- 1 <= words.length <= 100
- 1 <= words[i].length <= 100
Need a hint?
Only the first differing character in adjacent words establishes an ordering edge.
Asked in real interviews
Candidates reported versions of Alien Dictionary from these company interviews. Some company questions are locked and open with Premium or XP.
- Determine order of alien alphabetCitadel
- Infer an Alien Alphabet from Sorted WordsByteDance
- Infer an Unknown Alphabet OrderMeta
Solution approach
Compare adjacent words, adding one edge at their first mismatch. Reject a longer word preceding its exact prefix. Deduplicate edges before counting indegrees. Topologically sort all observed characters, including isolated ones; a cycle prevents consuming them all.
Complexity
O(total input characters + V + E) time and O(V + E) auxiliary space.
Python reference solution
from collections import deque
def alienOrder(words):
edges = {char: set() for word in words for char in word}
incoming = dict.fromkeys(edges, 0)
for first, second in zip(words, words[1:]):
for a, b in zip(first, second):
if a != b:
if b not in edges[a]:
edges[a].add(b)
incoming[b] += 1
break
else:
if len(first) > len(second):
return ''
queue = deque(char for char in edges if incoming[char] == 0)
order = []
while queue:
char = queue.popleft()
order.append(char)
for following in edges[char]:
incoming[following] -= 1
if incoming[following] == 0:
queue.append(following)
return ''.join(order) if len(order) == len(edges) else ''
JavaScript solution
function alienOrder(words) {
const edges = new Map(), incoming = new Map();
for (const word of words) for (const c of word) {
if (!edges.has(c)) { edges.set(c, new Set()); incoming.set(c, 0); }
}
for (let i = 1; i < words.length; i++) {
const first = words[i - 1], second = words[i];
let j = 0;
while (j < Math.min(first.length, second.length) && first[j] === second[j]) j++;
if (j === Math.min(first.length, second.length)) {
if (first.length > second.length) return '';
} else if (!edges.get(first[j]).has(second[j])) {
edges.get(first[j]).add(second[j]);
incoming.set(second[j], incoming.get(second[j]) + 1);
}
}
const queue = [];
for (const [c, count] of incoming) if (count === 0) queue.push(c);
for (let head = 0; head < queue.length; head++) {
for (const next of edges.get(queue[head])) {
incoming.set(next, incoming.get(next) - 1);
if (incoming.get(next) === 0) queue.push(next);
}
}
return queue.length === edges.size ? queue.join('') : '';
}
Java solution
import java.util.*;
class Solution {
public String alienOrder(String[] words) {
Map<Character, Set<Character>> edges = new HashMap<>();
Map<Character, Integer> incoming = new HashMap<>();
for (String word : words) for (char c : word.toCharArray()) {
edges.putIfAbsent(c, new HashSet<>()); incoming.putIfAbsent(c, 0);
}
for (int i = 1; i < words.length; i++) {
String first = words[i - 1], second = words[i];
int j = 0, limit = Math.min(first.length(), second.length());
while (j < limit && first.charAt(j) == second.charAt(j)) j++;
if (j == limit) {
if (first.length() > second.length()) return "";
} else if (edges.get(first.charAt(j)).add(second.charAt(j))) {
char next = second.charAt(j);
incoming.put(next, incoming.get(next) + 1);
}
}
Queue<Character> queue = new ArrayDeque<>();
for (char c : incoming.keySet()) if (incoming.get(c) == 0) queue.add(c);
StringBuilder order = new StringBuilder();
while (!queue.isEmpty()) {
char c = queue.remove(); order.append(c);
for (char next : edges.get(c)) {
incoming.put(next, incoming.get(next) - 1);
if (incoming.get(next) == 0) queue.add(next);
}
}
return order.length() == edges.size() ? order.toString() : "";
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
string alienOrder(vector<string> &words) {
unordered_map<char, unordered_set<char>> edges;
unordered_map<char, int> incoming;
for (const string& word : words) for (char c : word) {
edges[c]; incoming.emplace(c, 0);
}
for (size_t i = 1; i < words.size(); i++) {
const string &first = words[i - 1], &second = words[i];
size_t j = 0, limit = min(first.size(), second.size());
while (j < limit && first[j] == second[j]) j++;
if (j == limit) {
if (first.size() > second.size()) return "";
} else if (edges[first[j]].insert(second[j]).second) incoming[second[j]]++;
}
queue<char> ready;
for (auto [c, count] : incoming) if (count == 0) ready.push(c);
string order;
while (!ready.empty()) {
char c = ready.front(); ready.pop(); order += c;
for (char next : edges[c]) if (--incoming[next] == 0) ready.push(next);
}
return order.size() == edges.size() ? order : "";
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 8 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[
[
"wrt",
"wrf",
"er",
"ett",
"rftt"
]
]wertf
[
[
"z",
"x"
]
]zx
[
[
"z",
"x",
"z"
]
][
[
"abc",
"ab"
]
][
[
"a",
"b"
]
]ab
Drafts are saved per language in this browser when storage is available.