↻one more pass.
Graphs · Hard

Alien Dictionary: the idea to remember.

Infer a character ordering from words already sorted in an unknown alphabet, or report that the ordering is inconsistent.

The source exercise may require LeetCode Premium. This original explanation and Java reference are free to use here.
Solve on LeetCode ↗

The core insight

Compare adjacent words and add an edge for their first differing characters, then topologically sort all characters.

Why it works

Only the first difference determines the ordering of a word pair. A topological order satisfies every collected precedence constraint.

The mistake to avoid

A longer word before its exact prefix is invalid. Deduplicate edges or indegrees will be inflated.

Time: O(total characters + E + V log V)Space: O(V + E)

Commented Java solution

Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.

String alienOrder(String[] words) {
    Map<Character, Set<Character>> edges = new HashMap<>();
    Map<Character, Integer> degree = new HashMap<>();
    for (String w : words) for (char c : w.toCharArray()) {
        edges.putIfAbsent(c, new HashSet<>()); degree.putIfAbsent(c, 0);
    }
    for (int i = 1; i < words.length; i++) {
        String a = words[i - 1], b = words[i];
        int j = 0, limit = Math.min(a.length(), b.length());
        while (j < limit && a.charAt(j) == b.charAt(j)) j++;
        if (j == limit) { if (a.length() > b.length()) return ""; }
        else if (edges.get(a.charAt(j)).add(b.charAt(j)))
            degree.put(b.charAt(j), degree.get(b.charAt(j)) + 1);
    }
    PriorityQueue<Character> ready = new PriorityQueue<>();
    for (char c : degree.keySet()) if (degree.get(c) == 0) ready.add(c);
    StringBuilder out = new StringBuilder();
    while (!ready.isEmpty()) {
        char c = ready.remove(); out.append(c);
        for (char next : edges.get(c)) if (degree.merge(next, -1, Integer::sum) == 0) ready.add(next);
    }
    return out.length() == degree.size() ? out.toString() : "";
}

Make the next connection

Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.