#720
Medium Algorithms Longest word in dictionary
Array Hash Table String Trie Sorting
54.5% acceptance
Feb 21, 2026
2080
1507
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 longest word with the smallest lexicographical order. If there is no answer, return the empty string.
Note that the word should be built from left to right with each additional character being added to the end of a previous word.
Solution
Rust
Time O(n)
Space O(1)
/*
* 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 longest word with the smallest lexicographical order. If there is no answer, return the empty string.
* Note that the word should be built from left to right with each additional character being added to the end of a previous word.
* Example 1:
* Input: words = ["w","wo","wor","worl","world"]
* Output: "world"
* Explanation: The word "world" can be built one character at a time by "w", "wo", "wor", and "worl".
* 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. However, "apple" is lexicographically smaller than "apply".
* Constraints:
* 1 <= words.length <= 1000
* 1 <= words[i].length <= 30
* words[i] consists of lowercase English letters.
*/
use std::collections::HashSet;
impl Solution {
pub fn longest_word(words: Vec<String>) -> String {
let set: HashSet<&str> = words.iter().map(|s| s.as_str()).collect();
let mut best = "";
for word in &words {
let ok = (1..word.len()).all(|i| set.contains(&word[..i]));
if ok && (word.len() > best.len() || (word.len() == best.len() && word.as_str() < best)) {
best = word;
}
}
best.to_string()
}
}