DSA interview question
Archaeologists found a dictionary from an alien civilisation: a list of words sorted lexicographically by the aliens' alphabet, whose letter order is unknown. Recover an order of the letters that's consistent with the list, or return "" if none exists. Each pair of adjacent words reveals at most one fact: at their first differing position, the first word's letter comes before the second's. Those facts form a directed graph, and any topological order of it is a valid alphabet. Using a min-heap picks the alphabetically smallest valid order, so the answer is unique.
Example: ["wrt", "wrf", "er", "ett", "rftt"] → "wertf".
string alienOrder(const vector<string>& words); // lexicographically smallest valid order, or ""
| Input | Output | Explanation |
|---|---|---|
["wrt","wrf","er","ett","rftt"] | "wertf" | t<f, w<e, r<t, e<r |
["z","x"] | "zx" | |
["ab","adc"] | "abcd" | Only b<d is known; c is free |
["z","x","z"] | "" | z<x and x<z: a cycle |
["abc","ab"] | "" | A longer word can't come before its own prefix |
(Confirm: letters are lowercase; the output contains exactly the letters that appear; when several orders fit, the lexicographically smallest is returned here.)
On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in