Alien Dictionary? The arrows hide in a sorted word list
A famous follow-up hides the graph: all you get is a list of words in an alien language, sorted by its alphabet.
Predict
In a list sorted in an unknown alphabet, kite comes right before kin. What does that pair tell you?
def letter_pairs(words): letters = {ch for word in words for ch in word} needs = [] for first, second in zip(words, words[1:]): for a, b in zip(first, second): if a != b: # b comes after a needs.append((b, a)) break else: if len(first) > len(second): raise ValueError(f"{first!r} comes before its own prefix {second!r}") return sorted(letters), needsletters, pairs = letter_pairs(["kite", "kin", "tin", "tee", "ink"])print(pairs)print(kahn_order(letters, pairs))
Alien Dictionary is on Airbnb's LeetCode tag list (1 source), and a prep site's OpenAI guide says one candidate got a graph problem like it (1 source). You get words sorted in an unknown alphabet, and return an order of the letters.
The arrows come from neighbors in the list. The first letter where two adjacent words differ says which letter comes first, and the letters after it say nothing:
Neighbors
First difference
So
kite, kin
t, n
t before n
kin, tin
k, t
k before t
tin, tee
i, e
i before e
tee, ink
t, i
t before i
The letters as tasks
The traps:
Every letter is a task, even one that's in no pair.
A word listed before its own prefix, ["note", "no"], is impossible input.
A cycle means the list isn't sorted in any alphabet.
The editor holds an empty letter_rule. Write it to read one rule from two neighboring words, the step letter_pairs takes for each pair.
Pick an answer above to see the rest
Instructions
1
Write letter_rule(first, second): the pair (a, b) from the first position where the words differ, meaning a comes before b.
2
When they don't differ, return None if first is no longer than second, and raise ValueError if it is longer.