Example 1
- Input
- words = ["wrt","wrf","er","ett","rftt"]
- Output
- "wertf"
Adjacent pairs give t before f, w before e, r before t, and e before r, chaining into w to e to r to t to f.
Sorted alien words reveal which letter precedes which other letter. Rebuild the full letter order from those clues, or return an empty string when the clues contradict each other.
You are given a list of strings words from an alien dictionary, sorted lexicographically by the rules of that language. Return each observed letter exactly once in alphabet order. Any valid order is accepted when multiple orders are possible.
Lexicographic comparison uses the first differing characters; if one word is a prefix of another, the shorter word comes first. Return an empty string when the clues contradict each other or a longer word wrongly precedes its own prefix.
1 <= words.length <= 1001 <= words[i].length <= 100words[i] holds only lowercase English letters.Adjacent pairs give t before f, w before e, r before t, and e before r, chaining into w to e to r to t to f.
The single differing pair puts z before x.
The clues demand z before x and x before z, which is a cycle, so no order exists.
No alphabet can put a longer word before its exact prefix. Reject this even though no character differs and no edge is added.
A single word imposes no precedence rules. Both ab and ba are valid, but each observed letter appears only once despite the repeated a.
Compare adjacent words at their first mismatch: wrt and wrf say t must precede f, regardless of later characters. Represent that clue as the directed edge t -> f. Example 1 also reveals w -> e, r -> t and e -> r, making w -> e -> r -> t -> f. An alphabet satisfying every edge is a topological order. Include letters with no edges too, reject a longer word before its own prefix, and detect cycles because no letter in a cycle can come before all the others.
Reveal DFS Postorder Topo Sort: intuition, complexity, and code
["abc","ab"], which is invalid on sight and returns "".["z","x","z"], where no letter ever runs out of predecessors.Pairwise precedence clues become directed edges, and peeling off predecessor-free nodes yields the global order or exposes the contradiction.