sagelearnai

Longest Word in Dictionary

Difficulty: Medium · Pattern: Tries · LeetCode #720

Return the longest word in words that can be built one character at a time from other words in words: every prefix of it must also be in the list. Break ties with the lexicographically smallest word. Return "" if there is none.

Examples

text
["w","wo","wor","worl","world"]                          →  "world"
["a","banana","app","appl","ap","apply","apple"]          →  "apple"   ("apply" ties but is larger)

Hints

  1. Sorting the words means every prefix comes before the words that extend it.
  2. Or: build a trie, then DFS only through nodes that end a word.

Approach

Sort + set: sort the words lexicographically, and keep a set built = {""}. For each word, if word[:-1] is in built, the word is buildable: add it, and update the best answer if it is strictly longer. Lexicographic order means that among equal lengths, the first one found is the smallest, which handles the tie-break for free.

Trie alternative: DFS from the root, stepping only into children marked as word ends, with children visited in alphabetical order. The deepest node reached first is the answer.

Complexity

Time: O(Σ len · log n) for the sort. Space: O(Σ len).

Python solution
def longestWord(words):
    built, best = {""}, ""
    for w in sorted(words):
        if w[:-1] in built:
            built.add(w)
            if len(w) > len(best):
                best = w
    return best
JavaScript solution
function longestWord(words) {
  const built = new Set(['']);
  let best = '';
  for (const w of [...words].sort()) {
    if (built.has(w.slice(0, -1))) {
      built.add(w);
      if (w.length > best.length) best = w;
    }
  }
  return best;
}