I knew the general shape of the solution: build a directed graph from adjacent word pairs, run topological sort.
Build a directed graph of character precedence by comparing adjacent words to extract ordering constraints, then perform a topological sort to find a valid alphabet order. If a cycle is detected or the constraints are inconsistent (e.g., a longer word precedes its prefix), return an empty string.
Pro tip: Explicitly handle edge cases like duplicate words, a word being a prefix of the next, and cycles—interviewers at Meta often test these to see if you consider invalid inputs. Also, clarify that the alphabet may contain letters not present in the words, but the output should only include letters that appear.
Iterate through adjacent word pairs and find the first differing character to establish a directed edge from the earlier character to the later one. If the first word is longer and is a prefix of the second, the ordering is invalid, so return an empty string.
Represent each unique character as a node and add directed edges for each precedence constraint. Track in-degrees for all nodes to prepare for topological sorting.
Use Kahn's algorithm (BFS with a queue) or DFS to produce a linear ordering of characters. Start with nodes that have zero in-degree and repeatedly remove them, adding to the result.
If the topological sort does not include all nodes (i.e., some nodes remain with non-zero in-degree), a cycle exists, meaning no valid ordering. Return an empty string in this case.
If all nodes are processed, return the characters in the order produced by the topological sort as a string. Otherwise, return an empty string.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.