Problem 420353 · medium · Phase 04 Non-Linear Data Structures

Longest Word Built One Letter at a Time

trie · DFS

Given a list of words, return the longest word that can be built one character at a time using other words of the list: every prefix of the answer (of length 1, 2, ...) must itself be in the list. If several words qualify with the same maximal length, return the lexicographically smallest. If no word qualifies return "".

Examples

Input:  words = ["w", "wo", "wor", "worl", "world"]
Output: "world"

Input:  words = ["a", "banana", "app", "appl", "ap", "apply", "apple"]
Output: "apple"
Explanation: "apple" and "apply" both build up from a, ap, app, appl; "apple" is smaller.

Constraints

  • 0 <= len(words) <= 10**4, non-empty lowercase words, total characters <= 10**5
  • Target: O(total characters)

Goals

  • Traverse a trie while only descending through complete words
  • Break ties by lexicographic order
Starting Python…