← Whiteboard questions

Alien Dictionary

Work out a letter order from a sorted word list

DSA, Hard, Advanced Graphs

Which structure or algorithm, and what does it cost.

Explorers found a word list written in an alien alphabet, and nobody knows the order of its letters. words is the list, already sorted by that order the way a dictionary is: compare two words at the first place they differ, and a word that is a prefix of another comes first. Return a string with every letter used in words exactly once, in an order that makes the list sorted. If several orders work, return the one that comes first when the answers are compared as normal a to z strings. If no order works, return an empty string.

Examples

Input words = ["tea","tee","ate","ant"]
Output "taen"
Why the rules are t before a, t before n and a before e. After t, the letters a and n are free and a is smaller, then e is free and beats n.
Input words = ["zoo"]
Output "oz"
Why one word gives no rule, so the letters come in normal order.
Input words = ["pole","po"]
Output ""
Why po is a prefix of pole but comes after it, which no letter order allows.

Constraints

Your answer must contain

Target Aim for O(C) time, where C is the total number of letters in all words.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

Compare each pair of neighbouring words at the first letter where they differ. What does that tell you about those two letters?

Hint 2 the approach

Draw each rule as an arrow from one letter to the letter that must come after it. What pattern of arrows would make any order impossible?

Hint 3 the key step

Count the rules each letter still waits on. Which letters can go first? What changes when you place one, and how would you see letters that can never be placed?

Walkthrough

Full walkthrough brute force to best

Brute force

Try every order of the letters, which is up to 26! of them. For each, check that the words are sorted under it, and keep the smallest string that passes. This only works for a few letters.

Best method

Only neighbouring words give rules. For each neighbouring pair, find the first position where the letters differ. The letter in the first word must come before the letter in the second. Record each rule once. If no letters differ and the first word is longer, the second word is a prefix that comes after its longer word, so return an empty string. Then order the letters with a topological sort. Count the rules waiting on each letter and keep a min-heap of the letters with a count of 0. Pop the smallest letter, add it to the answer and lower the count of every letter that follows it. A letter that reaches 0 joins the heap. Taking the smallest ready letter each time gives the smallest valid order. A letter inside a circle of rules never reaches 0, so if the answer is shorter than the set of letters, return an empty string.

Hand trace

Example 1: the neighbouring pairs give the rules a before e (tea, tee), t before a (tee, ate) and t before n (ate, ant). The waiting counts are t 0, e 1, a 1 and n 1, so the heap holds [t]. Take t: a and n drop to 0, so the heap is [a, n]. Take a: e drops to 0, so the heap is [e, n]. Take e, then n. The answer is "taen".

Code

import heapq
def letter_order(words):
    after = {c: set() for w in words for c in w}      # after[x] = letters that must come after x
    waiting = {c: 0 for c in after}                   # rules each letter still waits on
    for a, b in zip(words, words[1:]):
        for x, y in zip(a, b):
            if x != y:
                if y not in after[x]:
                    after[x].add(y)
                    waiting[y] += 1
                break
        else:
            if len(a) > len(b):
                return ""                             # a word cannot come before its own prefix
    ready = [c for c in waiting if waiting[c] == 0]
    heapq.heapify(ready)
    order = []
    while ready:
        c = heapq.heappop(ready)
        order.append(c)
        for y in after[c]:
            waiting[y] -= 1
            if waiting[y] == 0:
                heapq.heappush(ready, y)
    return "".join(order) if len(order) == len(waiting) else ""

Time and memory

O(C) time, where C is the total number of letters: each neighbouring pair is scanned once, and the heap holds at most 26 letters. Memory is constant beyond the input, because there are at most 26 letters and 650 rules.

Common mistakes

  • Comparing every pair of words. Neighbouring pairs give all the rules, and the other pairs add nothing.
  • Forgetting the prefix case. A longer word that comes before its own prefix cannot be sorted, so return an empty string.
  • Keeping only the letters that appear in a rule. A letter in a word with no rule, such as the z in a list of one word, still belongs in the answer.
  • Counting one rule twice but lowering the count once. Record each rule once, or the letter never reaches 0.

Related problems

More Advanced Graphs problems
Alien Dictionary: hints, walkthrough and Python solution