You are given a list of words sorted according to the rules of an unknown alien alphabet that uses lowercase English letters. Recover one valid character order that is consistent with the sorted list.
For this question, make the output deterministic: if multiple valid orders exist, return the lexicographically smallest valid order among them. Return an empty string if the word list is invalid or the implied precedence rules contain a cycle. Every distinct letter that appears in words must appear exactly once in the answer.
Input / output
words: string[]string containing each distinct character once, or "" if invalidExamples
words = ["wrt","wrf","er","ett","rftt"] returns "wertf".words = ["z","x"] returns "zx".words = ["abc","ab"] returns "" because a longer word cannot appear before its own prefix.Constraints
1 <= words.length <= 1001 <= words[i].length <= 100words[i] contains only lowercase English lettersTarget complexity
O(total characters + unique letters log unique letters) time.Hints
Follow-up How would the solution change if the interviewer only needed any valid order instead of the lexicographically smallest one?