Longest Word in Dictionary — LeetCode #720 (Medium)
Tags: Array, Hash Table, String, Trie, Sorting
Related patterns: Hash Map, Array
Brute Force approach
Time complexity: O(n²). Space complexity: O(1).
In this approach, we will check each word in the list to see if all of its prefixes exist in the list. This is a straightforward method but can be inefficient as it requires multiple checks for each word.
The time complexity is O(n²) because for each word (n), we check all its prefixes (up to n). The space complexity is O(1) since we only use a few variables to store the longest word.
- Step 1: Initialize a variable to store the longest valid word.
- Step 2: For each word in the list, check if all prefixes of that word exist in the list.
- Step 3: If a word is valid and longer than the current longest word, update the longest word.
- Step 4: If two words are of the same length, keep the lexicographically smaller one.
1. Start with words = ["w", "wo", "wor", "worl", "world"].
2. Initialize longest = "".
3. Check 'w': valid (longest = 'w').
4. Check 'wo': valid (longest = 'wo').
5. Check 'wor': valid (longest = 'wor').
6. Check 'worl': valid (longest = 'worl').
7. Check 'world': valid (longest = 'world'). Final longest = 'world'.
Optimal Solution approach
Time complexity: O(n log n). Space complexity: O(n).
This approach uses a set to store the words for quick lookup. By sorting the words first, we ensure that we can build longer words in lexicographical order efficiently.
The time complexity is O(n log n) due to the sorting step, while the space complexity is O(n) for storing the words in a set.
- Step 1: Sort the words array lexicographically.
- Step 2: Initialize a set to store the words and a variable for the longest word.
- Step 3: Iterate through the sorted words and check if the current word can be formed by its prefixes in the set.
- Step 4: If valid, update the longest word.
- Step 5: Add the current word to the set.
1. Start with words = ["w", "wo", "wor", "worl", "world"].
2. Sort words: ["w", "wo", "wor", "worl", "world"].
3. Initialize longest = "" and wordSet = {}.
4. Check 'w': valid (longest = 'w'). Add 'w' to set.
5. Check 'wo': valid (longest = 'wo'). Add 'wo' to set.
6. Check 'wor': valid (longest = 'wor'). Add 'wor' to set.
7. Check 'worl': valid (longest = 'worl'). Add 'worl' to set.
8. Check 'world': valid (longest = 'world'). Add 'world' to set. Final longest = 'world'.
Key Insights
- Sorting the words helps in checking prefixes in lexicographical order.
- Using a set allows for O(1) average time complexity for lookups.
Common Mistakes
- Not checking all prefixes correctly.
- Forgetting to handle the lexicographical order when lengths are the same.
Interview Tips
- Always consider edge cases, such as single-character words.
- Explain your thought process clearly while coding.
- Don't forget to test your solution with multiple inputs.