hardGraphsGraphs

Alien Dictionary

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

Signals to notice

derive ordering from sorted word listcharacters have unknown precedencetopological sort

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.

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.

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.

Graphs Pattern