Infer an Unknown Alphabet Order
Company: Meta
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates a candidate's competency in graph-based reasoning, inference of ordering constraints from sequences of strings, and algorithmic manipulation of characters and relations.
Constraints
- 0 <= len(words) <= 10^4
- 1 <= len(word) <= 100 for each word when words is non-empty
- The total number of characters across all words is at most 10^5
- Each word contains only lowercase English letters, so the number of distinct letters K is at most 26
Examples
Input: (["wrt", "wrf", "er", "ett", "rftt"],)
Expected Output: "wertf"
Explanation: The constraints are t -> f, w -> e, r -> t, and e -> r, which produce the order wertf.
Input: (["abc", "ab"],)
Expected Output: ""
Explanation: A longer word appears before its exact prefix, so the input is invalid.
Input: (["z", "x", "z"],)
Expected Output: ""
Explanation: From z before x we get z -> x, and from x before z we get x -> z, which forms a cycle.
Input: ([],)
Expected Output: ""
Explanation: There are no words and therefore no characters to order.
Input: (["abc", "abc"],)
Expected Output: "abc"
Explanation: There are no ordering constraints between characters, so the lexicographically smallest valid order is abc.
Input: (["za", "zb", "ca", "cb"],)
Expected Output: "abzc"
Explanation: The constraints are a -> b and z -> c. The lexicographically smallest topological order is abzc.
Input: (["z", "x"],)
Expected Output: "zx"
Explanation: The first differing characters imply z -> x, so the order must be zx.
Hints
- Compare only adjacent words. The first position where they differ gives you one directed ordering constraint.
- After building a graph of character dependencies, use topological sorting. Tracking indegrees helps detect cycles, and a min-heap gives the lexicographically smallest valid order.