Problem Description
Given an array of strings words, find the longest string such that every prefix of the string is also in words. If there are multiple answers with the same length, return the lexicographically smallest one. If no valid string exists, return an empty string.
Key Insights
- Use a hash set for O(1) look-up to check if a prefix exists.
- Sorting the list lexicographically ensures that when candidates of the same length are encountered, the lexicographically smallest word is chosen.
- Iterate through each word and check if every prefix (from index 1 up to word.length-1) exists in the set.
Space and Time Complexity
Time Complexity: O(n * l) where n is the number of words and l is the maximum word length (since for each word all prefixes are checked)
Space Complexity: O(n * l) for storing words in a hash set
Solution
We solve the problem by first inserting all words into a hash set for quick prefix verification. Next, we sort the words lexicographically so that in cases of ties on the string length, the lexicographically smallest word is naturally considered first. For each word, we check if every prefix is present in the hash set. If a word passes this check and meets the conditions of being longer or lexicographically smaller (when lengths match), we update our result.