PPractick

DSA interview question

Alien Dictionary

Hard · Data structures · Topics: graph, bfs, topological sort, string

The problem

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".

Function signature

string alienOrder(const vector<string>& words);  // lexicographically smallest valid order, or ""

Test cases

InputOutputExplanation
["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.)

How interviewers phrase it

Clarifying questions to ask

  1. Should letters with no constraints be included? (Yes, every letter that appears.)
  2. What if the input is inconsistent? (Return "".)
  3. Which order if several fit? (Any; this version returns the smallest.)

Follow-ups to expect

  1. "Why only adjacent pairs?"
  2. "Why only the first differing letter?"
  3. "What about the prefix case?"
  4. "How is a cycle detected?"
  5. "Complexity?"

Practise questions like this with a real engineer

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 interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in