InterviewPrepKit

Home / Coding / Advanced Graphs

Alien Dictionary

hard Original ↗
Solving tips
  • Sorted-word-list ordering constraints signal a topological sort: each adjacent pair gives one edge (first differing char: a before b), and non-adjacent pairs add nothing.
  • Handle the prefix trap up front: if a word is a prefix of the previous word (e.g. 'abc' before 'ab'), no order is valid, so return ''.
  • Use Kahn's BFS (in-degree queue) and detect a cycle by checking if fewer letters were emitted than exist; remember to seed every letter, including those with no constraints.
  • Target O(C) time over total characters and O(1) space since there are at most 26 letters and 26^2 edges.

Problem

An alien language uses lowercase English letters, but with its own unknown alphabet order. You’re given a list of words that is claimed to be sorted lexicographically by that alien alphabet.

Recover and return a string containing every letter that appears in words, arranged in an order consistent with the sorting. If several orders are consistent, any one is accepted. If no order can explain the given list (the claim is contradictory), return "".

Lexicographic rules are the usual ones: words are compared at the first differing position; if there is no differing position, the shorter word must come first.

Examples

  • words = ["wrt","wrf","er","ett","rftt"]"wertf" — pairs give t<f, w<e, r<t, e<r; chaining them: w, e, r, t, f.
  • words = ["z","x"]"zx" — the single comparison says z comes before x.
  • words = ["z","x","z"]"" — z<x and x<z is a contradiction (a cycle).
  • words = ["abc","ab"]"" — a longer word may not precede its own prefix in any alphabet.

Constraints

  • 1 <= len(words) <= 100
  • 1 <= len(words[i]) <= 100
  • Only lowercase English letters, so at most 26 distinct characters.

Think about it first

Hint 1 Each adjacent pair of words yields at most one fact: at the first position where they differ, the first word's letter precedes the second word's letter. Non-adjacent pairs add nothing new.
Hint 2 Those facts are directed edges "a before b" between letters — you're being asked for a linear order compatible with all edges. That is a topological sort, and an answer exists iff the graph has no cycle. Watch the special case where the two words never differ: if the first is longer, the input is invalid immediately.
Hint 3 Kahn's algorithm: count in-degrees, repeatedly output any letter with in-degree 0 and decrement its neighbors. If you output fewer letters than exist, a cycle consumed the rest — return "". Remember letters with no constraints at all must still appear in the output.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.