Took me longer than I'd like to admit to see this was just topological sort on a DAG of character constraints.
Model the problem as a directed graph where each character is a node and edges represent ordering constraints derived from adjacent word pairs. Then perform a topological sort to find a valid character order, detecting cycles and invalid prefix cases along the way.
Pro tip: Clarify edge cases upfront: if a word is a prefix of the previous word, return empty string immediately. Also, mention that multiple valid orders may exist, so any topological order is acceptable.
Check if any word is a prefix of the previous word; if so, return empty string. Also handle empty input or single word by returning any order of unique characters.
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. Track all unique characters as nodes.
Perform a topological sort on the graph (e.g., using Kahn's algorithm or DFS). If a cycle is detected, return an empty string.
If topological sort succeeds, return the characters in sorted order as a string. Otherwise, return empty string.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.