Longest Word in Dictionary

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

Given an array of strings words representing an English dictionary, return the longest word in words that can be built one character at a time by other words in words.

If there is more than one possible answer, return the one that is lexicographically smallest. If there is no answer, return the empty string "".

Note that the word should be built from left to right, with each new word adding one letter to the previous word.

Examples

Example 1:

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

Output: "world"

Explanation: The word "world" can be built one character at a time: "w" -> "wo" -> "wor" -> "worl" -> "world". Each intermediate word exists in the dictionary.

Example 2:

Input: words = ["a","banana","app","appl","ap","apply","apple"]

Output: "apple"

Explanation: Both "apply" and "apple" can be built from other words in the dictionary. "apple" is lexicographically smaller than "apply", so it is the answer.

Example 3:

Input: words = ["abc","bc","ab","abcd"]

Output: ""

Explanation: No word can be built one character at a time because none of the single-character prefixes ("a" or "b") exist in the dictionary.

Constraints

  • 1 <= words.length <= 1000
  • 1 <= words[i].length <= 30
  • words[i] consists of lowercase English letters
Source: Trie pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle