Alien Dictionary

Work out the letter order of an unknown alphabet from a list of words sorted by it.

An alien language uses the lowercase English letters, but in an unknown order. Given a list of words from its dictionary, already sorted by that order, return a string of the letters in a valid order, or "" if no order fits. If several orders work, return any of them.

Example 1
Input: words = ["wrt", "wrf", "er", "ett", "rftt"]
Output: "wertf"
Example 2
Input: words = ["z", "x"]
Output: "zx"
Example 3
Input: words = ["z", "x", "z"]
Output: ""
Explanation: z comes before x, and x comes before z. No order can satisfy both.
Solution

The Idea

In an English dictionary, "cat" comes before "cow". Both words start with c, and the first place they differ is the second letter, a against o. That is why "cat" is listed first: a comes before o in the alphabet. The t and the w at the end play no part.

This problem runs that reasoning backwards. The words are sorted by an alphabet nobody has told us, and we want the alphabet. In Example 1, "wrt" and "wrf" share "wr" and first differ at the third letter, so t comes before f. "wrf" and "er" differ right at the first letter, so w comes before e.

Look at the picture below. In the part labelled "the sorted words", each word is compared with the word under it, the first letters that differ are highlighted, and the rule they give sits between the two words.

The sorted words wrt, wrf, er, ett, rftt with the first different letters of each neighbouring pair highlighted, giving t before f, w before e, r before t and e before r. On the right the rules are arrows forming the chain w, e, r, t, f, and no arrow comes into w, so w goes first.

The four pairs give four separate rules: t before f, w before e, r before t and e before r. The answer, though, is one string with all five letters. How do we line the letters up so that every rule holds?

Draw each rule as an arrow from the letter that comes first to the letter that comes after it, as in the part of the picture labelled "the rules as arrows". No arrow comes into w, so no rule puts another letter before it, and w can go first. With w placed, the rule w before e is met, and e has no other arrow coming in, so e goes next. Repeating this gives r, t and f: the order "wertf".

Letters joined by one-way arrows like these form a directed graph: each letter is a point, called a node, and each arrow is an edge. A row of letters in which every arrow points forward, from an earlier letter to a later one, is called a topological order.

Example 3 shows when there is no answer. The words "z", "x", "z" give z before x and then x before z. Those two arrows form a loop, called a cycle, so z and x each always have an arrow coming in, and neither can ever go first.

Solution Approach

Turning that idea into code means deciding which words to compare, how to read a rule from two words, how to store the rules, how to build the order, and how to notice a cycle.

Which words to compare

Do we need to compare every word with every other word? That works, but the number of pairs grows with the square of the list's length, and the extra pairs teach nothing new. In a sorted list, a rule from two words far apart already follows from the rules between the words in between. In Example 1, "wrt" and "er" say w before e, and the neighbours "wrf" and "er" say the same. So each word is compared only with the word right after it.

Reading a rule from two words

How does a pair of neighbouring words give a rule? Walk along both from the start while their letters match. At the first position where they differ, the letter in the earlier word comes before the letter in the later word. The letters after that position say nothing, just as the t and w in "cat" and "cow" said nothing.

Sometimes the shorter word runs out before any difference appears, because it matches the start of the longer word. A word like that is called a prefix of the longer one. "ab" before "abc" is fine in every alphabet, since a prefix always comes first, and the pair gives no rule. "abc" before "ab" is the other way round. No alphabet sorts the words like that, so the answer is "" straight away.

Storing the rules

Where do the rules go? Each of the 26 letters gets a set of the letters that must come after it. A list like this, with one entry per node naming where its edges lead, is called an adjacency list. For Example 1 it reads w: {e}, e: {r}, r: {t}, t: {f} and f: {}.

Next to it, an array counts for each letter how many arrows come into it, which is the number of rules that put some other letter before it. This count is called the letter's indegree. In Example 1, w has indegree 0 and every other letter has indegree 1.

Two pairs can give the same rule. In the list "ac", "ab", "zc", "zb", both "ac" with "ab" and "zc" with "zb" say c before b. The set keeps b once, and the count goes up only when the set takes in a new letter, so each rule is counted once.

Some letters appear in no rule at all, like the z in a list with the single word "z". They still belong in the answer, so a separate array of 26 flags marks every letter that appears in the words.

Building the order

How does "take a letter with no arrow coming in" become a loop? Keep a queue of the letters whose indegree is 0. Take one out and add it to the answer. Then lower the indegree of each letter in its set by one, because one rule that held it back is now met. A letter that reaches 0 joins the queue. This way of building a topological order is called Kahn's algorithm.

Noticing a cycle

What happens in Example 3? z and x start with indegree 1, so the queue starts empty and the loop places nothing. In general, the letters on a cycle never reach indegree 0 and never enter the queue. The answer then holds fewer letters than appear in the words, and that is the sign to return "".

Java Solution

The method alienOrder works in these steps:

  1. First, mark every letter that appears in the words in seen, a boolean array with one entry per letter, so a letter that is in no rule still reaches the answer.
  2. Create the adjacency list after, a list of 26 sets, where after.get(x) holds the letters that come after letter x. Create the array indegree next to it, all zeros.
  3. Compare each word a with the next word b in a loop. Inside it, a counter j moves past the letters the two words share, up to len, the length of the shorter word.
  4. If j reaches len, one word is a prefix of the other: return "" when a is the longer one, and otherwise go on to the next pair. If not, the letters at position j give the rule from before to. Add to to the set of from, and raise indegree[to] only when the set did not have it yet.
  5. Go through the letters from a to z. Count the ones that appear in a variable named letters, and put those with indegree 0 into ready, an ArrayDeque used as a first-in, first-out queue.
  6. While ready is not empty, take a letter c out of it and append it to the StringBuilder named order. Lower the indegree of each letter in the set of c, and add a letter to ready when its indegree reaches 0.
  7. Finally, return order if it holds all the letters. If it is shorter, some letters were stuck on a cycle, so return "".

The main method runs the three examples, a single word, a list where two pairs give the same rule, and a prefix pair in both orders.

Java
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class AlienDictionary {

    public static String alienOrder(String[] words) {
        boolean[] seen = new boolean[26];                 // which letters appear at all
        for (String w : words) {
            for (char c : w.toCharArray()) {
                seen[c - 'a'] = true;
            }
        }

        List<Set<Integer>> after = new ArrayList<>();     // after.get(x): letters that follow x
        for (int i = 0; i < 26; i++) {
            after.add(new HashSet<>());
        }
        int[] indegree = new int[26];                     // rules that put a letter after another
        for (int i = 0; i + 1 < words.length; i++) {
            String a = words[i];
            String b = words[i + 1];
            int len = Math.min(a.length(), b.length());
            int j = 0;
            while (j < len && a.charAt(j) == b.charAt(j)) {
                j++;                                      // skip the shared beginning
            }
            if (j == len) {
                if (a.length() > b.length()) {
                    return "";                            // "abc" before "ab" fits no order
                }
                continue;                                 // "ab" before "abc" gives no rule
            }
            int from = a.charAt(j) - 'a';
            int to = b.charAt(j) - 'a';
            if (after.get(from).add(to)) {                // count each rule once
                indegree[to]++;
            }
        }

        Deque<Integer> ready = new ArrayDeque<>();        // letters with nothing left before them
        int letters = 0;
        for (int c = 0; c < 26; c++) {
            if (seen[c]) {
                letters++;
                if (indegree[c] == 0) {
                    ready.add(c);
                }
            }
        }
        StringBuilder order = new StringBuilder();
        while (!ready.isEmpty()) {
            int c = ready.poll();
            order.append((char) ('a' + c));
            for (int d : after.get(c)) {
                if (--indegree[d] == 0) {
                    ready.add(d);
                }
            }
        }
        return order.length() == letters ? order.toString() : "";   // shorter means a cycle
    }

    private static void show(String... words) {
        System.out.println(String.join(", ", words) + " -> \"" + alienOrder(words) + "\"");
    }

    public static void main(String[] args) {
        show("wrt", "wrf", "er", "ett", "rftt");
        show("z", "x");
        show("z", "x", "z");
        show("z");
        show("ac", "ab", "zc", "zb");
        show("ab", "abc");
        show("abc", "ab");
    }
}

Running it prints:

Output
wrt, wrf, er, ett, rftt -> "wertf"
z, x -> "zx"
z, x, z -> ""
z -> "z"
ac, ab, zc, zb -> "aczb"
ab, abc -> "abc"
abc, ab -> ""

The first three lines give "wertf", "zx" and "", as in the three examples. For "z" alone there are no pairs and no rules, yet the answer is "z", because seen marked it. The list "ac", "ab", "zc", "zb" gives the rules a before z and c before b, with c before b found twice but counted once. Both a and c start with indegree 0, the pass from a to z meets a first, and the answer is "aczb".

The last two lines are the prefix pair. "ab" before "abc" gives no rule, so all three letters start in the queue and come out as "abc". "abc" before "ab" gives "" from the prefix check. That check is easy to leave out, treating the pair like "ab" and "abc" and moving on. A version that does that prints "abc" for this list, an alphabet for words that no alphabet can sort.

Complexity

The work is one read through the words to find the rules, then Kahn's algorithm on at most 26 letters.

  • Time: O(C) for C characters in all the words, because marking seen reads each character once, each pair of neighbours is read up to the shorter word, and Kahn's algorithm handles at most 26 letters.
  • Space: O(1) besides the input, because seen and indegree have 26 entries, the sets hold at most 26 × 26 rules, and the queue and the answer hold at most 26 letters.

Kahn's algorithm on its own, for any directed graph, is explained in Topological Sort.