Leetcode 720. Longest Word in Dictionary
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.
words
?words
is empty?Assuming the words array won’t be too large and we can handle it within typical memory and computation time constraints.
set<string>
to efficiently check if a prefix exists.Here is the C++ code implementing the above strategy:
#include <iostream>
#include <vector>
#include <string>
#include <set>
#include <algorithm>
using namespace std;
string longestWord(vector<string>& words) {
// Sort words by length and lexicographically
sort(words.begin(), words.end(), [](const string &a, const string &b) {
return a.length() == b.length() ? a < b : a.length() < b.length();
});
set<string> built;
string longest = "";
for (const string &word : words) {
if (word.length() == 1 || built.find(word.substr(0, word.length() - 1)) != built.end()) {
built.insert(word);
if (word.length() > longest.length()) {
longest = word;
}
}
}
return longest;
}
int main() {
vector<string> words = {"w","wo","wor","worl","world"};
cout << longestWord(words) << endl; // Expected output: "world"
return 0;
}
Thus, the overall time complexity is (O(n \log n)).
The space complexity is (O(n)) for storing the words in the set.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?