Python coding

Longest word built one letter at a time

Given a list words, return the longest word of the list that can be built one letter at a time, with every step also in the list: its first letter alone is in words, and so are its first two letters, its first three, and so on up to the whole word. So a one-letter word always qualifies. If several are equally long, return the alphabetically smallest; if none qualifies, return "".

Words use lowercase a–z and have at least one letter; words may be empty or contain repeats.

  • longest_buildable(["a","ap","app","appl","apple","apply","b"]) → "apple"
  • longest_buildable(["dot","do","d","dog","cat"]) → "dog"
  • longest_buildable(["ab","abc","bcd"]) → ""
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Insert every word in a trie and store the word itself at the node where it ends. A buildable word is a path from the root in which every node carries that mark.

Hint 2

Run a DFS from the root that steps only onto children with an end mark, and keep the best word seen: longer wins, and on equal length the alphabetically smaller one.

Solution and why it works
pythonO(T), T = total letters in words · O(T) for the trie
def longest_buildable(words: list[str]) -> str:
    root = {}
    for w in words:
        node = root
        for ch in w:
            node = node.setdefault(ch, {})
        node["$"] = w                            # the whole word ends here
    best, stack = "", [root]
    while stack:
        node = stack.pop()
        for ch, child in node.items():
            if ch != "$" and "$" in child:       # step only onto nodes where a word ends
                word = child["$"]
                if len(word) > len(best) or (len(word) == len(best) and word < best):
                    best = word
                stack.append(child)
    return best

In a trie, the prefixes of a word are exactly the nodes on its path, so "every prefix is a word" becomes "every node on the path has an end mark". A DFS that only steps onto marked nodes visits precisely the buildable words, each node once. Traps: the word's own end mark is not enough, every node above it needs one too (without "moo", "moon" doesn't count and the answer is "mo"), and ties go to the alphabetically smaller word, so compare when the lengths are equal.