Sponsored
Sponsored
This approach involves sorting the words array. By sorting, words that could potentially be built upon would appear earlier in the list. After sorting, we use a set to keep track of words that can be built character by character.
The process is as follows:
This is efficient due to the pre-sorting which allows easy checking and ensures we are building words correctly by the constraints given.
Time complexity: O(N log N + N * M), where N is the number of words and M is the average length of the words. Sorting takes O(N log N) and checking prefixes takes O(N * M).
Space complexity: O(N * M), where M is the length of the longest word.
1#include <iostream>
2#include <vector>
3#include <string>
4#include <unordered_set>
5#include <algorithm>
6
7using namespace std;
8
9string longestWord(vector<string>& words) {
10 sort(words.begin(), words.end(), [](const string &a, const string &b) {
11 return a.size() == b.size() ? a < b : a.size() < b.size();
12 });
13 unordered_set<string> built;
14 built.insert("");
string res;
for (string &word : words) {
if (built.find(word.substr(0, word.size() - 1)) != built.end()) {
built.insert(word);
if (word.size() > res.size()) res = word;
}
}
return res;
}
int main() {
vector<string> words = {"w", "wo", "wor", "worl", "world"};
cout << longestWord(words) << endl;
return 0;
}
This approach uses C++ STL library features to sort and manage an unordered_set
for fast lookup. The words are sorted first and the dictionary validates if each current word can be built from previously existing words in the sorted list. This ensures efficient lookup and insertion.
This approach uses a Trie (prefix tree) to store the words. By utilizing this data structure, we aim to verify if a word can be constructed by progressively building on its prefixes.
The steps are:
This combines efficient storage and lookup, with Prefix trees naturally lending themselves to this problem due to their structure.
Time complexity: O(N * M), where creating the Trie and checking word validity both operate over each character of every word.
Space complexity: O(N * M) for the Trie data structure.
1class TrieNode:
2
This Python solution involves first inserting all words into a Trie structure and then checking each sorted word to verify that every prefix exists within the Trie. The check is aided by the use of an end_of_word
flag to determine the presence of complete valid prefixes every step of the way.