Given a list of words, write a program to find the longest word made of other words in the list. If there are more than one answer, return the one that has smallest lexicographic order. If no answer, return an empty string.
Example:
Input: ["cat","banana","dog","nana","walk","walker","dogwalker"]
Output: "dogwalker"
Explanation: "dogwalker" can be made of "dog" and "walker".
Note:
0 <= len(words) <= 100
1 <= len(words[i]) <= 100
Solutions
Solution 1: Hash Table + Sorting + DFS
Note that in the problem, each word can actually be reused.
We can use a hash table \(\textit{s}\) to store all the words, then sort the words in descending order of length, and if the lengths are the same, sort them in ascending lexicographical order.
Next, we iterate through the sorted list of words. For each word \(\textit{w}\), we first remove it from the hash table \(\textit{s}\), then use depth-first search \(\textit{dfs}\) to determine if \(\textit{w}\) can be composed of other words. If it can, we return \(\textit{w}\).
The execution logic of the function \(\textit{dfs}\) is as follows:
If \(\textit{w}\) is empty, return \(\text{true}\);
Iterate through all prefixes of \(\textit{w}\). If a prefix is in the hash table \(\textit{s}\) and \(\textit{dfs}\) returns \(\text{true}\), then return \(\text{true}\);
If no prefix meets the condition, return \(\text{false}\).
If no word meets the condition, return an empty string.
The time complexity is \(O(m \times n \times \log n + n \times 2^M)\), and the space complexity is \(O(m \times n)\). Here, \(n\) and \(m\) are the length of the word list and the average length of the words, respectively, and \(M\) is the length of the longest word.