Problem Statement
Alien Dictionary
Imagine you find a dictionary from an alien planet. It uses our English letters, but the letters are sorted in a different order than ours. You are given a list of words, and they are already sorted by the alien's rules. Your job is to figure out the alien alphabet order and return it as a string. If the order is impossible (the words contradict each other), return an empty string.
Signals to notice
Brute force first
Try all possible orderings and check consistency. Factorial possibilities for character ordering. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.
The key insight
Build a directed graph: compare adjacent words to find ordering constraints (first differing character gives an edge). Then topological sort the graph. If a cycle exists, no valid ordering. where C = total characters across all words. Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.
Trace it on words = ["wrt","wrf","er","ett","rftt"]
Build edges from adjacent pairs: wrt|wrf -> t->f; wrf|er -> w->e; er|ett -> r->t; ett|rftt -> e->r
adj = {w:{e}, r:{t}, t:{f}, f:{}, e:{r}}; visited={}, result=[]
dfs(w): visit e -> visit r -> visit t -> visit f (no nei) done result=[f]; t done result=[f,t]; r done result=[f,t,r]; e done result=[f,t,r,e]; w done result=[f,t,r,e,w]
dfs(r),dfs(t),dfs(f): all already visited=True, no change
dfs(e): already visited=True; no cycle found anywhere
result=[f,t,r,e,w]; reverse -> 'wertf'
return "wertf"What must stay true
Adjacent words in the sorted list reveal exactly one ordering constraint — the first position where they differ tells you which character comes first. Topological sort linearizes all such constraints. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.
Shape of the loop
build adj: for each adjacent pair (w1,w2), at first differing char add edge c1->c2 dfs(node): mark node in-progress (False); for nei in adj[node]: if dfs(nei) is False -> cycle mark node done (True); append node to result; return True for c in adj: if dfs(c) is False: return "" return reversed(result) joined
Pseudocode only — the full worked solution lives in the Solution tab.
Easy way to go wrong
Comparing non-adjacent words — only adjacent pairs give reliable constraints. Also, if word A is a prefix of word B but A comes after B, the input is invalid. The fix is usually to return to the meaning of each move, not just the steps themselves.