Alien Dictionary
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
An alien language uses lowercase English letters, but in an unknown order. You're given a list of words from its dictionary, sorted by the alien alphabet.
Return a string of all the letters that appear in the words, in an order consistent with the sorting. If several orders work, return any of them. If the words contradict each other, so that no order works, return "".
Understand the problem
- Think of a normal dictionary:
"apple"comes before"apply"because, at the first position where they differ,ecomes beforey. The alien dictionary works the same way, but you don't know its alphabet. You have to work it out from the sorted words. - Only the first position where two neighboring words differ tells you anything.
- If one word is the beginning of the other (a prefix), the shorter one must come first:
"ab"before"abc". If the longer one comes first, the input is impossible. - Letters with no clues at all can go anywhere, but they still must appear in your answer.
Example 1
Input: words = ["wrt", "wrf", "er", "ett", "rftt"]
Output: "wertf"From neighboring pairs: t before f, w before e, r before t, e before r. Chain them: w, e, r, t, f.
Example 2
Input: words = ["z", "x", "z"]
Output: ""z before x, and then x before z. Impossible.
Example 3
Input: words = ["abc", "ab"]
Output: """ab" is a prefix of "abc", so it should have come first.
Constraints
1 <= words.length <= 1001 <= words[i].length <= 100
Hints
Stuck? Open one hint at a time. Each one gives away a little more than the last.
The idea in one sentence
Compare each pair of neighboring words to learn "letter A comes before letter B" rules, then order all the letters so every rule is respected (a topological sort), returning "" if the rules contradict each other.
Step 1: turn the sorted words into rules
Only neighboring words give information, and only at their first difference:
| Pair | First difference | Rule |
|---|---|---|
"wrt" / "wrf" | t / f | t before f |
"wrf" / "er" | w / e | w before e |
"er" / "ett" | r / t | r before t |
"ett" / "rftt" | e / r | e before r |
Letters after the first difference tell you nothing: in "wrf" vs "er", the rs are in the same position, but the words were already decided by w vs e.
The prefix trap: if the two words match all the way to the end of the shorter one, there's no rule. But if the longer one comes first (like "abc" then "ab"), the dictionary is invalid: return "" immediately.
Step 2: it's Course Schedule
Make each letter a node and each rule an arrow:
A valid alphabet is an order of the letters where every arrow points forward. That's a topological sort, exactly like ordering courses by their prerequisites. Use the same in-degree method (Kahn's algorithm):
- Give every letter that appears in any word an in-degree (how many rules say something comes before it). Include letters with no rules, with in-degree 0.
- Start a queue with all letters of in-degree 0.
- Repeatedly take a letter, add it to the answer, and lower the in-degree of every letter it points to. Any that reach 0 join the queue.
- If the answer has every letter, return it. If some are missing, they're stuck in a cycle (like
z → x → z): return"".
Don't count a rule twice: the same rule can appear from several word pairs. Keep each letter's successors in a set, and only raise the in-degree when the rule is new.
Step by step
Example 1. In-degrees: w 0, e 1, r 1, t 1, f 1. Queue: [w].
| Take | Answer so far | Unlocks | Queue after |
|---|---|---|---|
w | w | e: 1 → 0 ✅ | [e] |
e | we | r: 1 → 0 ✅ | [r] |
r | wer | t: 1 → 0 ✅ | [t] |
t | wert | f: 1 → 0 ✅ | [f] |
f | wertf | nothing | [] |
All 5 letters are placed: "wertf".
The code
The reference solution is below, with comments on every important line.
How fast is it?
With C = the total number of characters in all the words:
- Time: O(C). Collecting letters and comparing neighboring words both read each character about once. The topological sort is tiny: at most 26 letters.
- Memory: O(1) in practice: at most 26 letters and 26 × 26 rules.
Common mistakes
- Comparing every pair of words, not just neighbors. Neighbors are enough, and they're what the sorting guarantees.
- Reading past the first difference. Only the first differing letter is a rule.
- Forgetting the prefix case (
["abc", "ab"]→""). - Dropping letters with no rules. Every letter that appears must be in the answer.
- Adding the same rule twice and inflating an in-degree, so a letter never reaches 0.
Going deeper
Topological sort shows up whenever things must happen in an order with dependencies: build systems compiling files, package managers installing libraries, spreadsheets recalculating cells. A DFS version also exists: add a letter to the order after all letters it points to are finished, then reverse.
Reference solution
/**
* @param {string[]} words
* @return {string}
*/
export default function alienOrder(words) {
// Graph of letters: successors.get(a) = letters that come after a.
// inDegree.get(b) = how many letters must come before b.
const successors = new Map()
const inDegree = new Map()
// Every letter that appears is a node, even letters with no rules.
for (const word of words) {
for (const char of word) {
if (!successors.has(char)) {
successors.set(char, new Set())
inDegree.set(char, 0)
}
}
}
// Each pair of NEIGHBORING words gives at most one rule, at their first difference.
for (let i = 0; i + 1 < words.length; i++) {
const first = words[i]
const second = words[i + 1]
const length = Math.min(first.length, second.length)
let j = 0
while (j < length && first[j] === second[j]) j++
if (j === length) {
// No difference: a longer word before its own prefix is impossible.
if (first.length > second.length) return ''
continue
}
const before = successors.get(first[j])
// Rule: first[j] comes before second[j]. Count it only once.
if (!before.has(second[j])) {
before.add(second[j])
inDegree.set(second[j], inDegree.get(second[j]) + 1)
}
}
// Topological sort (as in Course Schedule): start with letters nothing comes before.
const queue = [...inDegree.keys()].filter((char) => inDegree.get(char) === 0)
for (let i = 0; i < queue.length; i++) {
for (const next of successors.get(queue[i])) {
inDegree.set(next, inDegree.get(next) - 1)
if (inDegree.get(next) === 0) queue.push(next) // everything before it is placed
}
}
// Letters left out are stuck in a cycle: the rules contradict each other.
return queue.length === inDegree.size ? queue.join('') : ''
}export default function alienOrder(words: string[]): string {
// Graph of letters: successors.get(a) = letters that come after a.
// inDegree.get(b) = how many letters must come before b.
const successors = new Map<string, Set<string>>()
const inDegree = new Map<string, number>()
// Every letter that appears is a node, even letters with no rules.
for (const word of words) {
for (const char of word) {
if (!successors.has(char)) {
successors.set(char, new Set())
inDegree.set(char, 0)
}
}
}
// Each pair of NEIGHBORING words gives at most one rule, at their first difference.
for (let i = 0; i + 1 < words.length; i++) {
const first = words[i]
const second = words[i + 1]
const length = Math.min(first.length, second.length)
let j = 0
while (j < length && first[j] === second[j]) j++
if (j === length) {
// No difference: a longer word before its own prefix is impossible.
if (first.length > second.length) return ''
continue
}
const before = successors.get(first[j])!
// Rule: first[j] comes before second[j]. Count it only once.
if (!before.has(second[j])) {
before.add(second[j])
inDegree.set(second[j], inDegree.get(second[j])! + 1)
}
}
// Topological sort (as in Course Schedule): start with letters nothing comes before.
const queue = [...inDegree.keys()].filter((char) => inDegree.get(char) === 0)
for (let i = 0; i < queue.length; i++) {
for (const next of successors.get(queue[i])!) {
inDegree.set(next, inDegree.get(next)! - 1)
if (inDegree.get(next) === 0) queue.push(next) // everything before it is placed
}
}
// Letters left out are stuck in a cycle: the rules contradict each other.
return queue.length === inDegree.size ? queue.join('') : ''
}from collections import deque
def alien_order(words: list[str]) -> str:
# Graph of letters: successors[a] = letters that come after a.
# in_degree[b] = how many letters must come before b. Every letter that appears is a node.
successors = {char: set() for word in words for char in word}
in_degree = {char: 0 for char in successors}
# Each pair of NEIGHBORING words gives at most one rule, at their first difference.
for first, second in zip(words, words[1:]):
for a, b in zip(first, second):
if a != b:
# Rule: a comes before b. Count it only once.
if b not in successors[a]:
successors[a].add(b)
in_degree[b] += 1
break
else:
# No difference (the loop never hit break): a longer word before its own prefix is impossible.
if len(first) > len(second):
return ""
# Topological sort (as in Course Schedule): start with letters nothing comes before.
queue = deque(char for char, degree in in_degree.items() if degree == 0)
order = []
while queue:
char = queue.popleft()
order.append(char)
for nxt in successors[char]:
in_degree[nxt] -= 1
if in_degree[nxt] == 0: # everything before it is placed
queue.append(nxt)
# Letters left out are stuck in a cycle: the rules contradict each other.
return "".join(order) if len(order) == len(in_degree) else ""