Alien Dictionary

Hard

Topics
GraphTopological SortBFS

There is a new alien language that uses the English alphabet. However, the order among letters is unknown. You are given a list of strings words from the alien language dictionary, where the strings are sorted lexicographically by the rules of this new language.

Return a string of the unique letters in the new alien language sorted in lexicographically increasing order by the new language's rules. If no valid order exists, return "".

Several orderings are usually valid, so this judge asks for one specific one. Resolve every free choice by taking the letter that is smallest in ordinary English alphabetical order: among the letters currently unconstrained, emit the alphabetically smallest first, and release a letter's dependents in alphabetical order too. For ["zy","zx"] the only constraint is y before x, and y and z are both free to go first, so the answer is "yzx".

Example 1

wrtwrferettrftt
Input:  words = ["wrt","wrf","er","ett","rftt"]
Output: "wertf"
Explanation: From "wrt" and "wrf": t < f. From "wrt" and "er": w < e. From "er" and "ett": r < t. From "ett" and "rftt": e < r.

Example 2

zx
Input:  words = ["z","x"]
Output: "zx"

Example 3

zxz
Input:  words = ["z","x","z"]
Output: ""
Explanation: Invalid ordering — cycle detected.

Example 4

zyzx
Input:  words = ["zy","zx"]
Output: "yzx"
Explanation: The only constraint is y before x. Both y and z start out unconstrained, and y is alphabetically smaller, so it goes first; z follows, then x once y has been placed.

Constraints

  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 100
  • words[i] consists of only lowercase English letters.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Each pair of adjacent words gives one ordering constraint between two characters. Build a directed graph of these constraints and run topological sort. If topo sort produces all characters, that is the answer. If a cycle exists, return empty string.

Approach

  1. Compare each pair of adjacent words. Find the first differing character — this gives an edge (a before b).
  2. Important: if a shorter word is a prefix of a longer word and comes after it, the ordering is invalid (return "").
  3. Build an adjacency list and in-degree map from all edges.
  4. Run Kahn's BFS: start with nodes of in-degree 0, dequeue and append to result, decrement neighbors' in-degree.
  5. If result length equals total unique characters, return result. Otherwise, a cycle exists — return "".

Dry Run

words = [wrt, wrf, er, ett, rftt]

Edges come from the FIRST differing letter of each adjacent pair, then stop:
  wrt  vs wrf    w=w, r=r, t!=f   -> t before f
  wrf  vs er     w!=e             -> w before e
  er   vs ett    e=e, r!=t        -> r before t
  ett  vs rftt   e!=r             -> e before r

indegree   w=0  e=1  t=1  f=1  r=1
frontier   [w]              (the only letter nothing points at)

pop w   out=w         w frees e        frontier=[e]
pop e   out=we        e frees r        frontier=[r]
pop r   out=wer       r frees t        frontier=[t]
pop t   out=wert      t frees f        frontier=[f]
pop f   out=wertf                      frontier=[]

all 5 letters emitted, so the order is consistent     answer wertf

The `break` after the first difference is load-bearing. wrt vs wrf says nothing
about r versus f -- only t before f. Comparing every position would invent
edges the dictionary never implied and can easily manufacture a false cycle.

Complexity

  • Time — O(C): where C is total length of all words (we scan each character once to build the graph, and topo sort is O(V+E) where V≤26 and E≤26²).
  • Space — O(1): since the alphabet is at most 26 characters, the graph is bounded by a constant.

Common Pitfalls

  • Forgetting to include characters that have no edges (isolated nodes must still appear in the output).
  • Missing the "prefix" invalid case: ["abc","ab"] is invalid.
  • Seeding the queue, or releasing a letter's dependents, in whatever order the graph happens to be stored in. Every valid topological order solves the underlying puzzle, but this judge accepts one, so both steps have to take the alphabetically smallest letter available — including for a single-word input, where there are no constraints at all and the answer is simply its letters in alphabetical order.

Full Solution — all languages

class Solution:
    def alienOrder(self, words):
        letters = set()
        for w in words:
            letters.update(w)
        adj = {c: set() for c in letters}
        indeg = {c: 0 for c in letters}
        for first, second in zip(words, words[1:]):
            for a, b in zip(first, second):
                if a != b:
                    if b not in adj[a]:
                        adj[a].add(b)
                        indeg[b] += 1
                    break
            else:
                if len(first) > len(second):
                    return ""
        frontier = sorted(c for c in letters if indeg[c] == 0)
        out = []
        while frontier:
            c = frontier.pop(0)
            out.append(c)
            freed = []
            for nxt in sorted(adj[c]):
                indeg[nxt] -= 1
                if indeg[nxt] == 0:
                    freed.append(nxt)
            frontier.extend(freed)
        return "".join(out) if len(out) == len(letters) else ""
SensAI
Beta
Tap the mic to stop voice mode