929. Longest Word in Dictionary (Trie)

MediumTreesTrieSortingHash

Given a list of words, return the longest word that can be built one character at a time, where every prefix of it (of every shorter length) is also present in the list. If several qualify, return the lexicographically smallest. If none qualifies, return an empty string. The input is a JSON array of words.

Input: A JSON array of words.

Output: Quoted string — the longest buildable word.

Examples

Example 1
Input: ["w","wo","wor","worl","world"]
Output: "world"
Explanation: Every prefix exists.
Example 2
Input: ["a","banana","app","appl","ap","apply","apple"]
Output: "apple"
Explanation: 'apple' is buildable and smallest among ties.
Example 3
Input: ["x"]
Output: "x"
Explanation: Single word.

Constraints

Asked by

MicrosoftAmazon
Solve this problem in the editor →