Tries Prefix trees
428. Longest Word With All Prefixes
You are given a list of lowercase words, words. Return the longest word in the list whose every prefix is
also in the list.
A prefix of a word is its first few letters, from one letter up to the whole word: "c", "ca" and "cat" are the prefixes of "cat". So "cat" counts only if "c" and "ca" are both words in the list too.
If several words of the greatest length count, return the one that comes first in alphabetical order. If no
word counts, return the empty string "". Answers are shown in double quotes, so an empty answer shows as
"".
Example 1
Input: words = ["top",
"t",
"toes",
"tap",
"to",
"tops",
"toe",
"topsoil"]
"toes"Explanation: "toes" and "tops" both count, since "t", "to", "toe" and "top" are all in the list. They have the same length, and "toes" comes first in alphabetical order. "tap" needs "ta", and "topsoil" needs "topso".
Example 2
Input: words = ["ab", "abc", "abcd"]
""Explanation: Every word starts with "a", but "a" itself is not in the list. So no word counts.
Example 3
Input: words = ["pine", "p", "pines", "pin"]
"p"Explanation: Three of the words start with "pi", but "pi" is not a word in the list. So "pin", "pine" and "pines" do not count, and only "p" does.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ words.length ≤ 1051 ≤ words[i].length, and all the words together hold at most105letterswords[i]holds only lowercase English letters
Clarifying questions
What you would ask an interviewer before writing any code.