The core idea clicked pretty fast: compare adjacent words, find the first character that differs, that gives you a directed edge.
Build a directed graph where each character is a node and edges represent the relative order derived from adjacent word pairs. Then perform a topological sort to find a valid character ordering, returning an empty string if a cycle is detected or if a word is a prefix of a previous word.
Pro tip: Explicitly handle the prefix violation case (e.g., 'abc' before 'ab') as an immediate invalid input, and mention that the graph may be disconnected, so you must include all unique characters from the input.
Check for prefix violations by comparing each word with its predecessor; if a word is shorter and a prefix of the previous word, return empty string. Collect all unique characters from the list to ensure the graph includes every character.
For each pair of adjacent words, find the first differing character and add a directed edge from the character in the first word to the character in the second word. If no differing character is found, the words are identical or one is a prefix (already handled).
Perform a topological sort on the graph using either Kahn's algorithm (BFS with in-degree) or DFS with cycle detection. If a cycle is detected, return an empty string.
If the topological sort succeeds, concatenate the characters in the order produced to form the alien alphabet string. If multiple valid orderings exist, any is acceptable.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.