hardGraphsGraphs

Alien Dictionary

hardTime: O(C)Space: O(1)

Recognize the pattern

derive ordering from sorted word listcharacters have unknown precedencetopological sort

Brute force idea

The naive version of Alien Dictionary sounds like this: 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.

Better approach

The deeper shift in Alien Dictionary is this: 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.

Key invariant

At the center of Alien Dictionary is one steady idea: 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.

Watch out for

One easy way to drift off course in Alien Dictionary is this: 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.

Graphs Pattern