AAI Agentic Handbook
Problem 47 · Graphs

Alien Dictionary

HardClassic DSA & systems
01Problem

Given a list of words sorted in an unknown alphabet's lexicographic order, return a string of the letters in a valid order, or empty string if the ordering is invalid.

02Key insight

Only the first differing character of each adjacent pair yields an edge; then topologically sort. Catch the invalid prefix case ("abc" before "ab") and cycles.

03Solution

Try it first.

TimeO(C) total characters
SpaceO(U^2) for U unique letters
tests.py · 4 passing
tests.pypython4 lines
assert alien_order(["wrt","wrf","er","ett","rftt"]) == "wertf"
assert alien_order(["z","x","z"]) == ""
assert alien_order(["abc","ab"]) == ""
assert sorted(alien_order(["z","z"])) == ["z"]
04Staff-level follow-up

How to tell if the order is unique? It is unique iff Kahn's queue never holds more than one node at a time.