Python coding

Alphabet from a sorted word list

A language uses the lowercase letters a–z, but in its own alphabetical order. words is a list of its words, already sorted by that order. Return a string with every letter that appears in words, each once, in an order consistent with the list. Whenever several letters could come next, take the one that comes first in the normal a–z alphabet, so the answer is unique. If no order can explain the list, return "".

As in any dictionary, a word comes after its own prefixes: ["ab", "a"] is invalid.

  • letter_order(["tap","tag","pat","gap"]) → "atpg"
  • letter_order(["cb","ca","ba"]) → "cba"
  • letter_order(["ab","a"]) → ""
  • letter_order(["x","y","x"]) → ""
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Every pair of neighbouring words tells you one thing: at the first position where they differ, the letter of the earlier word comes first. That is an edge in a graph of letters.

Hint 2

Topologically sort the letters with Kahn's algorithm, keeping the ready letters in a min-heap so the a–z tie-break holds. Include the letters that have no edges.

Hint 3

Two ways to fail: a longer word placed before its own prefix, and a cycle, which shows up as fewer letters in the output than in the input.

Solution and why it works
pythonO(C + U²), C = total characters, U = distinct letters (≤ 26) · O(U²)
import heapq


def letter_order(words: list[str]) -> str:
    after = {ch: set() for word in words for ch in word}
    for a, b in zip(words, words[1:]):
        for x, y in zip(a, b):
            if x != y:
                after[x].add(y)              # a set: a repeated pair counts once
                break
        else:
            if len(a) > len(b):
                return ""                    # a word placed before its own prefix
    indeg = {ch: sum(ch in nexts for nexts in after.values()) for ch in after}
    ready = [ch for ch in after if indeg[ch] == 0]
    heapq.heapify(ready)
    order = []
    while ready:
        ch = heapq.heappop(ready)            # smallest ready letter first
        order.append(ch)
        for nxt in after[ch]:
            indeg[nxt] -= 1
            if indeg[nxt] == 0:
                heapq.heappush(ready, nxt)
    return "".join(order) if len(order) == len(after) else ""

A sorted list fixes the order of two letters only at the first position where neighbouring words differ, so each adjacent pair adds at most one edge; later letters say nothing. Kahn's algorithm with a min-heap then emits the letters, smallest ready one first. Count each edge once, or a repeated pair leaves an in-degree that never reaches zero. Return "" when a word precedes its own prefix or when the output has fewer letters than the input, which means a cycle.