Determine order of alien alphabet
Company: Citadel
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Technical Screen
Quick Answer: This question evaluates the ability to infer ordering constraints among characters, model dependencies from ordered examples, and reason about edge cases in lexicographic sequences. Commonly asked in Coding & Algorithms interviews, it assesses both practical algorithmic implementation and conceptual understanding within the domains of string processing and graph-based ordering problems.
Constraints
- 1 <= len(words) <= 10^4
- 1 <= len(words[i]) <= 100
- Each word contains only lowercase English letters
- There are at most 26 distinct characters across all words
Examples
Input: (["wrt", "wrf", "er", "ett", "rftt"],)
Expected Output: "wertf"
Explanation: From adjacent comparisons we get w -> e, e -> r, r -> t, and t -> f, so a valid order is "wertf".
Input: (["z", "x"],)
Expected Output: "zx"
Explanation: Comparing "z" and "x" gives z -> x, so the only valid order is "zx".
Input: (["ba", "bc", "ac", "cab"],)
Expected Output: "bac"
Explanation: The comparisons imply a -> c and b -> a, so the full valid order is b -> a -> c.
Input: (["abc", "ab"],)
Expected Output: ""
Explanation: "abc" appears before its strict prefix "ab", which is impossible in a valid lexicographic ordering.
Input: (["z", "x", "z"],)
Expected Output: ""
Explanation: The list implies z -> x and x -> z, creating a cycle, so no valid alphabet exists.
Input: (["aaa"],)
Expected Output: "a"
Explanation: There is only one distinct character, so the answer is simply "a".
Hints
- Only the first differing character between two adjacent words tells you anything about the order.
- Build a directed graph of character precedence rules, then use topological sorting. Don't forget to check the invalid prefix case.