Alien Dictionary solution explained

To solve Alien Dictionary, compare each pair of neighbouring words, find the first position where they differ, and record that the letter in the first word comes before the letter in the second. Those rules form a directed graph over the letters, and a topological sort of that graph (Kahn's algorithm) gives a valid alphabet. Return an empty string if a longer word appears before its own prefix or the rules contain a cycle. It runs in O(C) time, where C is the total number of characters.

By Published 8 min read

The problem, rephrased

An unfamiliar language uses ordinary lowercase letters, but in a different alphabetical order. You are handed a list of words from its dictionary, already sorted by that hidden order. Work out an ordering of all the letters that appear in the words which is consistent with the list. If several orders fit, any one is accepted. If no order can produce the list, return an empty string.

Word lists made up for this page
WordsWhat they tell youA valid answer
tk, tq, kq, kz, qzk before q, t before k, q before z"tkqz" (the only one)
wa, wb, ea before b, w before e"awbe", "wabe", and others
xy, yx, xzx before y, then y before x"" (a cycle)
mnp, mna longer word before its own prefix"" (impossible in any order)
snothing to compare"s"
Word lists made up for this page. Scroll sideways on a small screen.

The last two rows are the traps. In any alphabet a prefix sorts before the longer word, so "mnp" can never come before "mn". And letters that never take part in a comparison, like "s" above, must still appear somewhere in the output.

Why interviewers ask it

Alien Dictionary is a favourite because the hard part is not the algorithm. Topological sort is standard; the interview is about turning a fuzzy description into a graph correctly. Interviewers listen for three things: that you take only the first difference from each adjacent pair, that you treat the prefix case as invalid, and that you detect cycles. They often ask how you would test it, since many outputs are correct and an exact string comparison would be the wrong check.

  • Is the order unique? Run Kahn's algorithm and check that the queue never holds more than one letter at a time.
  • Verify a given alphabet. The reverse task: given an order, check the list is sorted. Map each letter to its rank and compare neighbours.
  • Course schedule. The same topological sort with the edges handed to you directly.
  • Smallest valid order. Replace the queue with a min-heap to get the lexicographically smallest answer by ordinary letter order.

Brute force: try every alphabet

With k distinct letters there are k! possible orders. For each, rank the letters and check that every adjacent pair of words is in order. Python compares lists element by element and treats a shorter prefix as smaller, so ranking each word into a list of numbers makes the check one line. This is hopeless beyond about ten letters, but it is a solid way to test the real solution on tiny inputs, and saying that out loud shows you think about verification.

from itertools import permutations

def sorted_under(words, rank):
    for first, second in zip(words, words[1:]):
        if [rank[c] for c in first] > [rank[c] for c in second]:
            return False
    return True

def alien_order_brute(words):
    letters = sorted({ch for w in words for ch in w})
    for perm in permutations(letters):
        rank = {ch: i for i, ch in enumerate(perm)}
        if sorted_under(words, rank):
            return "".join(perm)
    return ""
Python: permutations. O(k! · C) time. Only for small tests.

The efficient approach: graph plus topological sort

Create a node for every letter that appears anywhere, with in-degree 0. For each adjacent pair of words, scan to the first position where they differ. If you find one, add an edge from the first word's letter to the second word's letter, but only if that edge is new, so the in-degree is not counted twice. If you run out of characters without a difference and the first word is longer, the list is impossible, so return the empty string. Then run Kahn's algorithm: start a queue with every zero in-degree letter, repeatedly pop one into the output, and decrement its neighbours, enqueuing any that reach zero. If the output ends up shorter than the number of letters, some letters were stuck in a cycle.

from collections import deque

def alien_order(words):
    graph = {ch: set() for w in words for ch in w}
    indegree = {ch: 0 for ch in graph}
    for first, second in zip(words, words[1:]):
        for a, b in zip(first, second):
            if a != b:
                if b not in graph[a]:
                    graph[a].add(b)
                    indegree[b] += 1
                break
        else:
            if len(first) > len(second):
                return ""
    queue = deque(ch for ch in graph if indegree[ch] == 0)
    order = []
    while queue:
        ch = queue.popleft()
        order.append(ch)
        for nxt in graph[ch]:
            indegree[nxt] -= 1
            if indegree[nxt] == 0:
                queue.append(nxt)
    return "".join(order) if len(order) == len(graph) else ""
Python: Kahn's algorithm. O(C) time, O(1) extra space for a fixed 26-letter alphabet.

The for-else in Python runs the else branch only when the inner loop finishes without a break, meaning no differing letter was found. That is exactly the moment to check the prefix rule. In the JavaScript version the same check is written with an explicit index.

function alienOrder(words) {
  const graph = new Map();
  const indegree = new Map();
  for (const w of words) {
    for (const ch of w) {
      if (!graph.has(ch)) {
        graph.set(ch, new Set());
        indegree.set(ch, 0);
      }
    }
  }
  for (let i = 0; i + 1 < words.length; i++) {
    const first = words[i];
    const second = words[i + 1];
    const len = Math.min(first.length, second.length);
    let j = 0;
    while (j < len && first[j] === second[j]) j++;
    if (j === len) {
      if (first.length > second.length) return "";
      continue;
    }
    const a = first[j];
    const b = second[j];
    if (!graph.get(a).has(b)) {
      graph.get(a).add(b);
      indegree.set(b, indegree.get(b) + 1);
    }
  }
  const queue = [...graph.keys()].filter((ch) => indegree.get(ch) === 0);
  const order = [];
  for (let head = 0; head < queue.length; head++) {
    const ch = queue[head];
    order.push(ch);
    for (const nxt of graph.get(ch)) {
      indegree.set(nxt, indegree.get(nxt) - 1);
      if (indegree.get(nxt) === 0) queue.push(nxt);
    }
  }
  return order.length === graph.size ? order.join("") : "";
}
JavaScript: the same graph with a Map of Sets and an array used as a queue.

A depth-first alternative also works: mark each letter white, grey (on the current path) or black (finished), and append a letter to the output after all its successors are finished, then reverse. Reaching a grey letter means a cycle. Both versions are linear; Kahn's algorithm is usually easier to explain, and the cycle check is just a length comparison.

Complexity

C characters in total, k distinct letters, n words
ApproachTimeExtra space
Try every permutationO(k! · C)O(k)
Compare all pairs of words, not just neighboursO(n² · L) for word length LO(k²) edges
Adjacent pairs plus Kahn's algorithmO(C + k²) at most, O(C) for a fixed alphabetO(k²) edges at most
Adjacent pairs plus three-colour DFSSameSame, plus recursion depth up to k
C characters in total, k distinct letters, n words. Scroll sideways on a small screen.

Comparing only neighbours is enough because sorted order is transitive: if every adjacent pair is in order, the whole list is in order, so non-adjacent pairs add no new information that the topological sort needs.

Edge cases

  • A longer word before its own prefix ("mnp" then "mn"): return the empty string.
  • Identical adjacent words: no edge and no error.
  • Letters that appear in no comparison: they have in-degree 0 and go into the output anyway.
  • The same pair of letters ordered twice by different word pairs: add the edge once.
  • A single word, or a list where every word is one repeated letter.
  • A cycle, including a two-letter one: the output is shorter than the letter count, so return the empty string.

Mistakes to avoid

  • Adding edges for every position where two words differ, not just the first. Later positions carry no ordering information.
  • Missing the prefix case, and returning some order for an impossible list.
  • Counting duplicate edges twice, so a letter's in-degree never reaches zero and a valid list looks cyclic.
  • Only creating graph nodes for letters that appear in edges, which drops isolated letters from the answer.
  • Checking the output against one expected string in tests, when several orders are correct.

How to explain it out loud

Fictional example

Turning words into edges
Candidate
Two neighbouring words agree up to some position. The first letter where they differ tells me one ordering rule; nothing after it matters.
Candidate
If there is no difference and the first word is longer, that cannot be sorted in any alphabet, so I return empty.
Candidate
The rules are edges in a graph of letters, so I need a topological order. I will use in-degrees and a queue; if I cannot place every letter, there was a cycle.
Interviewer
How would you test it?
Candidate
Not by comparing strings, since many answers are valid. I would check every letter appears once and that the word list is sorted under my order, and compare against brute force on tiny alphabets.

Is Graph Bipartite is the other graph-modelling problem in this set, using colouring instead of ordering. Number of Islands practices graph traversal on a grid. All Nodes Distance K in a Binary Tree is another case where you build the graph you need before searching it, and Valid Parentheses is a lighter warm-up on processing sequences in order.

Where Natively fits

This problem rewards practicing the reasoning before the code. Rehearsing on Mac or Windows, you can let Natively read the word list from a screenshot and ask it only for the step you are missing, for instance why the prefix case is invalid, then finish the graph yourself. The transcript it keeps of your mock round shows whether you described how you would test a problem with many right answers. See the AI interview assistant for details.

Questions people ask

How do you solve the Alien Dictionary problem?

Compare each pair of adjacent words and take the first position where they differ as an ordering rule between two letters. Build a graph from those rules and return a topological sort of all letters.

When does Alien Dictionary return an empty string?

When the rules contain a cycle, or when a longer word comes directly before its own prefix, which no alphabet can produce.

What is the time complexity of Alien Dictionary?

O(C), where C is the total number of characters in all words, plus at most O(k squared) edges for k distinct letters, which is constant for a fixed alphabet.

Is the answer to Alien Dictionary unique?

Not always. Letters without a rule between them can go in either order, so test with a validator rather than one expected string.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP