Try it first — give it 40 minutes
0/4 revealedStuck? Take one hint at a time. The struggle is where the pattern sticks.
The problem in plain English
This is a LeetCode Premium problem. LintCode 892 is the same problem and free to practise on. Read its statement to see how it wants ties between several valid orders broken.
An alien language uses lowercase English letters, but in an unknown order. You get words, a list that is sorted by that alien order, the same way a dictionary is sorted in ours. Return a string containing every letter that appears in words, each exactly once, arranged in an order consistent with the list. If several orders work, any one is fine. If no order can make this list sorted, return "". There are up to 100 words of up to 100 letters each.
Example: ["wrt","wrf","er","ett","rftt"] → "wertf".
"Sorted" means the usual dictionary rule: compare letter by letter, and the first difference decides. If one word is a prefix of the other, the shorter one comes first. So "ab" before "abc" is fine, but "abc" before "ab" is impossible in any alphabet.
Start with brute force
Try every ordering of the distinct letters. For each one, check whether the list is sorted under it. With k distinct letters that's k! orderings. 10 letters already gives 3.6 million, and 26 letters is about 4 × 10²⁶. It's hopeless beyond tiny inputs, but it nails down what "valid" means: the list must be sorted under the order.
Building the intuition
Compare two words the way a dictionary does: wrt and wrf. The ws match and the rs match, then t versus f. They're different, and wrt comes first, so t comes before f. That's all this pair tells you. Letters after the first difference tell you nothing, because the first difference already decided the order.
What about non-adjacent words, like the first and the last? If the list is sorted, then each word ≤ the next word, and the chain of adjacent comparisons implies every other comparison. So adjacent pairs give you every rule you need.
Now write the rules from the example:
wrt/wrf→t < fwrf/er→w < eer/ett→r < tett/rftt→e < r
Each rule is a directed edge x → y. You need to line up the letters so that every edge points forward. That's a topological sort, the same thing you did with courses and prerequisites in Course Schedule. Letters are courses, and rules are prerequisites.
Kahn's algorithm does it. Keep each letter's indegree (how many rules say something must come before it). Start with the letters whose indegree is 0. Output one, delete its outgoing edges, and any letter whose indegree drops to 0 becomes available. If letters are still left when you run out, they're stuck in a cycle (like a < b and b < a), and no alphabet exists.
The optimal approach
- Mark every letter that appears in any word as
present. - For each adjacent pair
(a, b):- find the first index
iwhere they differ; - if there's no difference and
ais longer thanb, return"", because a word came before its own prefix; - otherwise, if they differ, add the edge
a[i] → b[i](skip it if it already exists) and incrementindegree[b[i]].
- find the first index
- Run Kahn's algorithm: put every present letter with indegree 0 in a queue, then pop, append to
order, and decrease each neighbour's indegree, enqueuing the ones that hit 0. - If
orderhas every present letter, return it. Otherwise there's a cycle, so return"".
Two subtle details:
- Duplicate rules.
t < fcan show up from several pairs. If you add the edge twice,f's indegree is 2, but Kahn's only removes it once, sofnever becomes free. That looks like a fake cycle. A 26 × 26 boolean matrix makes deduplication trivial. - Letters with no rules. A letter that never appears in any rule still has to be in the answer. That's why we track
presentseparately instead of only collecting letters from edges.
The code
Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.
from collections import deque
class Solution:
def alienOrder(self, words: List[str]) -> str:
# letters are nodes 0..25; edge[x][y] means "x comes before y"
present = [False] * 26
for w in words:
for ch in w:
present[ord(ch) - ord("a")] = True
edge = [[False] * 26 for _ in range(26)]
indegree = [0] * 26
# only ADJACENT words give rules, and only at their first differing letter
for a, b in zip(words, words[1:]):
i = 0
while i < len(a) and i < len(b) and a[i] == b[i]:
i += 1
if i == len(a) or i == len(b): # one word is a prefix of the other
if len(a) > len(b):
return "" # "abc" before "ab" can never be sorted
continue # "ab" before "abc" says nothing
x, y = ord(a[i]) - ord("a"), ord(b[i]) - ord("a")
if not edge[x][y]: # skip duplicate rules so indegrees stay right
edge[x][y] = True
indegree[y] += 1
# Kahn's algorithm: repeatedly output a letter nothing else must precede
queue = deque(c for c in range(26) if present[c] and indegree[c] == 0)
order = []
while queue:
x = queue.popleft()
order.append(chr(x + ord("a")))
for y in range(26):
if edge[x][y]:
indegree[y] -= 1
if indegree[y] == 0:
queue.append(y)
# letters left over are stuck in a cycle: no valid order exists
return "".join(order) if len(order) == sum(present) else ""class Solution {
public:
string alienOrder(vector<string>& words) {
// letters are nodes 0..25; edge[x][y] means "x comes before y"
vector<bool> present(26, false);
for (auto& w : words)
for (char ch : w) present[ch - 'a'] = true;
vector<vector<bool>> edge(26, vector<bool>(26, false));
vector<int> indegree(26, 0);
// only ADJACENT words give rules, and only at their first differing letter
for (int k = 0; k + 1 < (int)words.size(); k++) {
const string& a = words[k];
const string& b = words[k + 1];
int i = 0;
while (i < (int)a.size() && i < (int)b.size() && a[i] == b[i]) i++;
if (i == (int)a.size() || i == (int)b.size()) { // one is a prefix of the other
if (a.size() > b.size()) return ""; // "abc" before "ab" is impossible
continue; // "ab" before "abc" says nothing
}
int x = a[i] - 'a', y = b[i] - 'a';
if (!edge[x][y]) { // skip duplicate rules so indegrees stay right
edge[x][y] = true;
indegree[y]++;
}
}
// Kahn's algorithm: repeatedly output a letter nothing else must precede
queue<int> q;
int letters = 0;
for (int c = 0; c < 26; c++) {
if (present[c]) letters++;
if (present[c] && indegree[c] == 0) q.push(c);
}
string order;
while (!q.empty()) {
int x = q.front();
q.pop();
order += char('a' + x);
for (int y = 0; y < 26; y++) {
if (edge[x][y] && --indegree[y] == 0) q.push(y);
}
}
// letters left over are stuck in a cycle: no valid order exists
return (int)order.size() == letters ? order : "";
}
};class Solution {
public String alienOrder(String[] words) {
// letters are nodes 0..25; edge[x][y] means "x comes before y"
boolean[] present = new boolean[26];
for (String w : words)
for (char ch : w.toCharArray()) present[ch - 'a'] = true;
boolean[][] edge = new boolean[26][26];
int[] indegree = new int[26];
// only ADJACENT words give rules, and only at their first differing letter
for (int k = 0; k + 1 < words.length; k++) {
String a = words[k], b = words[k + 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()) { // one is a prefix of the other
if (a.length() > b.length()) return ""; // "abc" before "ab" is impossible
continue; // "ab" before "abc" says nothing
}
int x = a.charAt(i) - 'a', y = b.charAt(i) - 'a';
if (!edge[x][y]) { // skip duplicate rules so indegrees stay right
edge[x][y] = true;
indegree[y]++;
}
}
// Kahn's algorithm: repeatedly output a letter nothing else must precede
Deque<Integer> queue = new ArrayDeque<>();
int letters = 0;
for (int c = 0; c < 26; c++) {
if (present[c]) letters++;
if (present[c] && indegree[c] == 0) queue.add(c);
}
StringBuilder order = new StringBuilder();
while (!queue.isEmpty()) {
int x = queue.poll();
order.append((char) ('a' + x));
for (int y = 0; y < 26; y++) {
if (edge[x][y] && --indegree[y] == 0) queue.add(y);
}
}
// letters left over are stuck in a cycle: no valid order exists
return order.length() == letters ? order.toString() : "";
}
}/**
* @param {string[]} words
* @return {string}
*/
var alienOrder = function (words) {
const A = "a".charCodeAt(0);
// letters are nodes 0..25; edge[x][y] means "x comes before y"
const present = new Array(26).fill(false);
for (const w of words) for (const ch of w) present[ch.charCodeAt(0) - A] = true;
const edge = Array.from({ length: 26 }, () => new Array(26).fill(false));
const indegree = new Array(26).fill(0);
// only ADJACENT words give rules, and only at their first differing letter
for (let k = 0; k + 1 < words.length; k++) {
const a = words[k], b = words[k + 1];
let i = 0;
while (i < a.length && i < b.length && a[i] === b[i]) i++;
if (i === a.length || i === b.length) { // one is a prefix of the other
if (a.length > b.length) return ""; // "abc" before "ab" is impossible
continue; // "ab" before "abc" says nothing
}
const x = a.charCodeAt(i) - A, y = b.charCodeAt(i) - A;
if (!edge[x][y]) { // skip duplicate rules so indegrees stay right
edge[x][y] = true;
indegree[y]++;
}
}
// Kahn's algorithm: repeatedly output a letter nothing else must precede
const queue = [];
let letters = 0;
for (let c = 0; c < 26; c++) {
if (present[c]) letters++;
if (present[c] && indegree[c] === 0) queue.push(c);
}
let order = "";
for (let head = 0; head < queue.length; head++) { // head pointer = O(1) dequeue
const x = queue[head];
order += String.fromCharCode(A + x);
for (let y = 0; y < 26; y++) {
if (edge[x][y] && --indegree[y] === 0) queue.push(y);
}
}
// letters left over are stuck in a cycle: no valid order exists
return order.length === letters ? order : "";
};Dry run
The edges from above are t → f, w → e, r → t, e → r. Indegrees: e 1, f 1, r 1, t 1, w 0.
| Step | Queue | Pop | Order | Indegrees that drop to 0 |
|---|---|---|---|---|
| start | w | |||
| 1 | w | w | w | e |
| 2 | e | e | we | r |
| 3 | r | r | wer | t |
| 4 | t | t | wert | f |
| 5 | f | f | wertf | none |
All 5 present letters are in the order, so return "wertf".
Complexity
- Time: O(C), where
Cis the total number of characters in all words. Each adjacent comparison stops at the first difference, so it costs at most the shorter word's length. Kahn's algorithm on 26 letters is a constant 26 × 26 at most. - Space: O(1). The alphabet is fixed at 26 letters, so the matrix and arrays have constant size.
Edge cases and traps
- A word before its own prefix, like
["abc", "ab"]. No alphabet fixes this. Return"". Forgetting this case is the most common wrong answer. - Comparing past the first difference. Only the first differing letter is a rule. Adding more creates false edges and fake cycles.
- Comparing non-adjacent words. It's unnecessary, and it's easy to get wrong.
- Duplicate edges inflating indegrees. Deduplicate them, or decrement once per copy you added.
- Dropping letters with no rules. In
["z", "z"]the answer is"z", not"". - A cycle.
["z", "x", "z"]givesz < xandx < z. Kahn's algorithm outputs nothing, so return"".
Say it in the interview
"Each adjacent pair of words gives at most one rule: the first letter where they differ. If there's no difference and the first word is longer, the input is invalid, so I return an empty string. The rules form a directed graph on letters, and any topological order is a valid alphabet. I run Kahn's algorithm with indegrees, deduplicating edges with a 26-by-26 matrix. If the output is missing any letter that appears, there's a cycle and I return an empty string. Time is linear in the total characters, and space is constant because the alphabet is fixed."
Follow-ups interviewers ask
- "Return the lexicographically smallest valid order." Replace the queue with a min-heap, so you always output the smallest available letter.
- "Is the order unique?" Only if the queue never holds more than one letter at a time. If it ever has two choices, several orders are valid.
- "Can you use DFS instead?" Yes. Post-order DFS with three colours (unvisited, in progress, done) detects a cycle when it meets an in-progress letter. Reverse the post-order to get the answer.
Practise the same idea
This is a bonus day of the free DSA plan 🐸
90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.
Get the full roadmap — free