LeetCode 720: Longest Word in Dictionary Solution
Master LeetCode problem 720 (Longest Word in Dictionary), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
720. Longest Word in Dictionary
Problem Explanation
Explanation
To solve this problem, we can use a HashSet to store all valid words. We then iterate through the given words array and check if all prefixes of the word exist in the HashSet. If it does, we add the word to the HashSet. Finally, we iterate through the words in the HashSet to find the longest word with the smallest lexicographical order.
Algorithm:
- Initialize an empty HashSet
wordSet. - Sort the given array of words lexicographically.
- Iterate through the sorted words array:
- Check if all prefixes of the word exist in
wordSet. - If they do, add the word to
wordSet.
- Check if all prefixes of the word exist in
- Iterate through the words in
wordSetto find the longest word with the smallest lexicographical order.
Time Complexity:
- Let n be the total number of characters in all words.
- Sorting the array of words takes O(m log m) time, where m is the number of words.
- Iterating through the words array and checking prefixes takes O(n) time.
- Iterating through the HashSet to find the result takes O(m) time.
- Therefore, the overall time complexity is O(n + m log m).
Space Complexity:
- The space complexity is O(n) to store the HashSet and sorted array of words.
Solution Code
class Solution {
public String longestWord(String[] words) {
Set<String> wordSet = new HashSet<>();
Arrays.sort(words);
String result = "";
for (String word : words) {
if (word.length() == 1 || wordSet.contains(word.substring(0, word.length() - 1))) {
wordSet.add(word);
if (word.length() > result.length()) {
result = word;
}
}
}
return result;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 720 (Longest Word in Dictionary)?
This page provides optimized solutions for LeetCode problem 720 (Longest Word in Dictionary) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 720 (Longest Word in Dictionary)?
The time complexity for LeetCode 720 (Longest Word in Dictionary) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 720 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 720 in Java, C++, or Python.