Skip to content
BytePatterns

Longest Word Built Letter by Letter

MediumTries#trie#dfs~25m

Problem

A word game lets a player grow a word one letter at a time, adding each letter to the end, and every intermediate step must itself be a word from the dictionary. Given the dictionary, return the longest word that can be built this way starting from a one-letter word. If several words tie on length, return the alphabetically smallest; if none can be built, return an empty string.

Examples

Input:  words = ["w", "wo", "wor", "worl", "world"]
Output: "world"
Input:  words = ["a", "banana", "app", "appl", "ap", "apply", "apple"]
Output: "apple"
Why:    "apply" is also buildable and just as long, but "apple" sorts first
Input:  words = ["cat", "ca"]
Output: ""
Why:    edge case, "c" is missing, so no chain can start

Hints

0 / 3

Stuck on the idea rather than the code? Trie Basics covers it.