Alien Dictionary
Hard
Topics
There is a new alien language that uses the English alphabet. However, the order among letters is unknown. You are given a list of strings words from the alien language dictionary, where the strings 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 no valid order exists, return "".
Several orderings are usually valid, so this judge asks for one specific one. Resolve every free choice by taking the letter that is smallest in ordinary English alphabetical order: among the letters currently unconstrained, emit the alphabetically smallest first, and release a letter's dependents in alphabetical order too. For ["zy","zx"] the only constraint is y before x, and y and z are both free to go first, so the answer is "yzx".
Example 1
Input: words = ["wrt","wrf","er","ett","rftt"] Output: "wertf" Explanation: From "wrt" and "wrf": t < f. From "wrt" and "er": w < e. From "er" and "ett": r < t. From "ett" and "rftt": e < r.
Example 2
Input: words = ["z","x"] Output: "zx"
Example 3
Input: words = ["z","x","z"] Output: "" Explanation: Invalid ordering — cycle detected.
Example 4
Input: words = ["zy","zx"] Output: "yzx" Explanation: The only constraint is y before x. Both y and z start out unconstrained, and y is alphabetically smaller, so it goes first; z follows, then x once y has been placed.
Constraints
- 1 <= words.length <= 100
- 1 <= words[i].length <= 100
- words[i] consists of only lowercase English letters.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Each pair of adjacent words gives one ordering constraint between two characters. Build a directed graph of these constraints and run topological sort. If topo sort produces all characters, that is the answer. If a cycle exists, return empty string.
Approach
- Compare each pair of adjacent words. Find the first differing character — this gives an edge (a before b).
- Important: if a shorter word is a prefix of a longer word and comes after it, the ordering is invalid (return "").
- Build an adjacency list and in-degree map from all edges.
- Run Kahn's BFS: start with nodes of in-degree 0, dequeue and append to result, decrement neighbors' in-degree.
- If result length equals total unique characters, return result. Otherwise, a cycle exists — return "".
Dry Run
words = [wrt, wrf, er, ett, rftt]
Edges come from the FIRST differing letter of each adjacent pair, then stop:
wrt vs wrf w=w, r=r, t!=f -> t before f
wrf vs er w!=e -> w before e
er vs ett e=e, r!=t -> r before t
ett vs rftt e!=r -> e before r
indegree w=0 e=1 t=1 f=1 r=1
frontier [w] (the only letter nothing points at)
pop w out=w w frees e frontier=[e]
pop e out=we e frees r frontier=[r]
pop r out=wer r frees t frontier=[t]
pop t out=wert t frees f frontier=[f]
pop f out=wertf frontier=[]
all 5 letters emitted, so the order is consistent answer wertf
The `break` after the first difference is load-bearing. wrt vs wrf says nothing
about r versus f -- only t before f. Comparing every position would invent
edges the dictionary never implied and can easily manufacture a false cycle.Complexity
- Time — O(C): where C is total length of all words (we scan each character once to build the graph, and topo sort is O(V+E) where V≤26 and E≤26²).
- Space — O(1): since the alphabet is at most 26 characters, the graph is bounded by a constant.
Common Pitfalls
- Forgetting to include characters that have no edges (isolated nodes must still appear in the output).
- Missing the "prefix" invalid case: ["abc","ab"] is invalid.
- Seeding the queue, or releasing a letter's dependents, in whatever order the graph happens to be stored in. Every valid topological order solves the underlying puzzle, but this judge accepts one, so both steps have to take the alphabetically smallest letter available — including for a single-word input, where there are no constraints at all and the answer is simply its letters in alphabetical order.
Full Solution — all languages
class Solution:
def alienOrder(self, words):
letters = set()
for w in words:
letters.update(w)
adj = {c: set() for c in letters}
indeg = {c: 0 for c in letters}
for first, second in zip(words, words[1:]):
for a, b in zip(first, second):
if a != b:
if b not in adj[a]:
adj[a].add(b)
indeg[b] += 1
break
else:
if len(first) > len(second):
return ""
frontier = sorted(c for c in letters if indeg[c] == 0)
out = []
while frontier:
c = frontier.pop(0)
out.append(c)
freed = []
for nxt in sorted(adj[c]):
indeg[nxt] -= 1
if indeg[nxt] == 0:
freed.append(nxt)
frontier.extend(freed)
return "".join(out) if len(out) == len(letters) else ""import java.util.*;
class Solution {
public String alienOrder(String[] words) {
TreeSet<Character> letters = new TreeSet<>();
for (String w : words) for (char c : w.toCharArray()) letters.add(c);
Map<Character, TreeSet<Character>> adj = new HashMap<>();
Map<Character, Integer> indeg = new HashMap<>();
for (char c : letters) {
adj.put(c, new TreeSet<>());
indeg.put(c, 0);
}
for (int i = 0; i + 1 < words.length; i++) {
String first = words[i], second = words[i + 1];
int minLen = Math.min(first.length(), second.length());
boolean split = false;
for (int j = 0; j < minLen; j++) {
if (first.charAt(j) != second.charAt(j)) {
if (adj.get(first.charAt(j)).add(second.charAt(j))) {
indeg.merge(second.charAt(j), 1, Integer::sum);
}
split = true;
break;
}
}
if (!split && first.length() > second.length()) return "";
}
Deque<Character> frontier = new ArrayDeque<>();
for (char c : letters) if (indeg.get(c) == 0) frontier.addLast(c);
StringBuilder out = new StringBuilder();
while (!frontier.isEmpty()) {
char c = frontier.pollFirst();
out.append(c);
List<Character> freed = new ArrayList<>();
for (char nxt : adj.get(c)) {
if (indeg.merge(nxt, -1, Integer::sum) == 0) freed.add(nxt);
}
for (char f : freed) frontier.addLast(f);
}
return out.length() == letters.size() ? out.toString() : "";
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: string alienOrder(vector<string>& words) {
set<char> letters;
for (auto& w : words) for (char c : w) letters.insert(c);
map<char, set<char>> adj;
map<char, int> indeg;
for (char c : letters) {
adj[c];
indeg[c] = 0;
}
for (size_t i = 0; i + 1 < words.size(); i++) {
const string& first = words[i];
const string& second = words[i + 1];
size_t minLen = min(first.size(), second.size());
bool split = false;
for (size_t j = 0; j < minLen; j++) {
if (first[j] != second[j]) {
if (!adj[first[j]].count(second[j])) {
adj[first[j]].insert(second[j]);
indeg[second[j]]++;
}
split = true;
break;
}
}
if (!split && first.size() > second.size()) return "";
}
deque<char> frontier;
for (char c : letters) if (indeg[c] == 0) frontier.push_back(c);
string out;
while (!frontier.empty()) {
char c = frontier.front();
frontier.pop_front();
out += c;
vector<char> freed;
for (char nxt : adj[c]) {
if (--indeg[nxt] == 0) freed.push_back(nxt);
}
for (char f : freed) frontier.push_back(f);
}
return out.size() == letters.size() ? out : "";
}
};/**
* @param {string[]} words
* @return {string}
*/ var alienOrder = function(words) {
const letters = new Set();
for (const w of words) for (const c of w) letters.add(c);
const adj = new Map(), indeg = new Map();
for (const c of letters) {
adj.set(c, new Set());
indeg.set(c, 0);
}
for (let i = 0; i + 1 < words.length; i++) {
const first = words[i], second = words[i + 1];
const minLen = Math.min(first.length, second.length);
let split = false;
for (let j = 0; j < minLen; j++) {
if (first[j] !== second[j]) {
if (!adj.get(first[j]).has(second[j])) {
adj.get(first[j]).add(second[j]);
indeg.set(second[j], indeg.get(second[j]) + 1);
}
split = true;
break;
}
}
if (!split && first.length > second.length) return "";
}
const frontier = [...letters].filter(c => indeg.get(c) === 0).sort();
let out = "";
while (frontier.length) {
const c = frontier.shift();
out += c;
const freed = [];
for (const nxt of [...adj.get(c)].sort()) {
indeg.set(nxt, indeg.get(nxt) - 1);
if (indeg.get(nxt) === 0) freed.push(nxt);
}
frontier.push(...freed);
}
return out.length === letters.size ? out : "";
};