Longest Word in Dictionary

Given an array of strings `words`, return the longest word in `words` that can be built one character at a time by other words in `words`: every prefix of it (of length 1, 2, ...) must also be in `words`. If there are several answers of the same length, return the one that is lexicographically smallest. If no word can be built, return the empty string.

30:00

Longest Word in Dictionary
medium
Free written solution
Topics
Companies

Given an array of strings words, return the longest word in words that can be built one character at a time by other words in words: every prefix of it (of length 1, 2, ...) must also be in words. If there are several answers of the same length, return the one that is lexicographically smallest. If no word can be built, return the empty string.

Example 1:
Input: {"words":["w","wo","wor","worl","world"]}
Output: world
Constraints:
  • 1≤words.length≤10001 \leq \text{words.length} \leq 1000

  • 1≤words[i].length≤301 \leq \text{words}[i].\text{length} \leq 30

  • words[i] consists of lowercase English letters.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"words":["w","wo","wor","worl","world"]}

Start with an empty trie. Each of the 5 words will be added as a path of letters, with its last node marked as a word end.

words (5)

w
wo
wor
worl
world

trie (ringed node = end of a word)

·

best =

""

Variables
VariableValue
words5
DepthFunction Call
Stack empty
0/17