Skip to the solution
HardDSA11 min read

Alien Dictionary: given sorted words in an alien language, how do you derive the character order?

739 views

The problem

Question presented to candidate: "You are given a list of words from an alien language, and the list is sorted in that language's alphabetical order. The letters are ordinary lowercase letters, but their order is unknown. Return a string with one possible ordering of the letters, or an empty string if no ordering is consistent with the list. Please write it in Python."

What a strong answer should cover:

  • Only adjacent words are compared, and only their first differing letters give a rule (an edge a -> b); letters after that carry no information.
  • The prefix trap: a longer word directly before its own prefix makes the input invalid.
  • A topological sort (Kahn) over the letters that appear, adding each edge once; a cycle means contradictory rules and the answer is "".
  • Complexity O(C + U^2) with C total characters and U at most 26 letters, and how to tell whether the order is unique.
  • Python specifics: zip(words, words[1:]) for adjacent pairs, for ... else to detect "no difference found", ord(ch) - 97 indexing, collections.deque, and "".join to build the answer.

Clarifying questions expected:

  • "Is any valid ordering acceptable, or do you want a specific one?"
  • "What should I return if the list is contradictory or a word comes before its own prefix?"
  • "Are all characters lowercase a to z?"

Code / implementation expected: Yes โ€” alienOrder(words) in Python: build edges from adjacent pairs, then Kahn's algorithm.

  • topological sort
  • graph
  • Google

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

11 min read ยท 11 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonDerive the alien alphabet: normal, contradictory and prefix cases
PythonIs the order unique, and does it really sort the words? (LeetCode 953 check)

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 141 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextHard

How do you find the largest rectangle in a histogram?

Continue