◀ THE GRIND — ADVANCED GRAPHS

Alien Dictionary

The drill: A list of words is claimed to already be sorted by some unknown alphabet's rules. Recover a letter ordering consistent with that claim, or report that no ordering could have produced this list.

THE BRIEFING — THE FULL DRILL, IN MY OWN WORDS

A list of words arrives in a fixed order, and the claim is that this order matches dictionary order under some alien alphabet whose letter-to-letter ranking is unknown.

The job is to recover one letter ordering that would make the list's order valid, using only the information adjacent words in the list can reveal. A contradictory list — one no single ordering could have produced — has to be reported instead.

One case invalidates any ordering outright, alphabet aside: a longer word sitting immediately before its own prefix can never be sorted correctly, no matter how the letters rank.

EX 01
words = ["b", "d", "f", "h"]
"bdfh"
SINGLE-LETTER WORDS, A DIRECT CHAIN
EX 02
words = ["ab", "ac", "b"]
"abc"
MULTI-CHAR WORDS STILL FULLY CHAIN THE ALPHABET
EX 03
words = ["z"]
"z"
ONE WORD, ONE LETTER — TRIVIALLY UNIQUE
THE HINTS — TAKE ONLY WHAT YOU NEED
HINT 1 THE NUDGE

Only ADJACENT words carry information — the first pair of words that differ pins down exactly one letter-before-letter fact. Everything else is noise you don't need to look at.

HINT 2 THE STRUCTURE

Every such fact is an edge: this letter precedes that letter. Once every adjacent pair has contributed its edge, the puzzle stops being about words entirely — it's about ordering the nodes of a graph so every edge points forward.

HINT 3 ONE STEP FROM THE ANSWER

Topologically sort the letter graph. Watch for the one edge case that isn't really a graph problem: a longer word sitting directly before its own prefix can never be valid, no matter the alphabet.

COACH'S BOARD — THE PATTERN, STEP BY STEP
SPELLING OUT THE ALPHABETPATTERN · TOPOLOGICAL SORT, KAHN'Swords: ab, ac, b
QUEUE
— empty —
STEP 1

Compare adjacent words: ab vs ac gives b before c; ac vs b gives a before b. Count in-degrees, then peel zero-indegree letters.

STEP 1 / 6 · ← → WORK TOO
THE SPLITS — TWO PACES, TWO LANGUAGES
grind/alien-dictionary.pyRACE PACE
LANG ▸
PACE ▸
class Solution:
    def alienOrder(self, words: List[str]) -> str:
        indegree = {c: 0 for w in words for c in w}
        graph = collections.defaultdict(set)
        for i in range(len(words) - 1):
            w1, w2 = words[i], words[i + 1]
            minlen = min(len(w1), len(w2))
            found = False
            for j in range(minlen):
                if w1[j] != w2[j]:
                    if w2[j] not in graph[w1[j]]:
                        graph[w1[j]].add(w2[j])
                        indegree[w2[j]] += 1
                    found = True
                    break
            if not found and len(w1) > len(w2):
                return ""
        queue = collections.deque([c for c in indegree if indegree[c] == 0])
        order = []
        while queue:
            c = queue.popleft()
            order.append(c)
            for nxt in graph[c]:
                indegree[nxt] -= 1
                if indegree[nxt] == 0:
                    queue.append(nxt)
        if len(order) < len(indegree):
            return ""
        return "".join(order)
TIME O(C)SPACE O(1)PYTHON · RACE PACE · 29 LN

✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED