Longest Word In Dictionary Problem
Description
LeetCode Problem 720. Given a list of strings words representing an English dictionary, find 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. If there is no answer, return the empty string.
All the strings in the input will only contain lowercase letters.
Example:
Input: words = ["w","wo","wor","worl", "world"]
Output: "world"
Explanation: The word "world" can be built one character at a time by "w", "wo", "wor", and "worl".
Solution
Approach: Sort and Build with a Hash Set
A word can be built one character at a time exactly when the word without its last letter can be built too (and a one-letter word can always be built). So if we look at the words in an order where every word comes after its prefixes, one check per word is enough.
Sorting lexicographically gives that order: a prefix is always smaller than any longer word that starts with it.
- Sort
words. - Keep a set
buildablethat starts with the empty string"", so one-letter words pass the check. - For each word, if
wordwithout its last character is inbuildable, addwordto the set, and if it is strictly longer than the best so far, make it the new best.
The tie-break comes for free: among buildable words of the same length, the lexicographically smallest one is seen first, and a later word of equal length never replaces it because we only replace on a strictly longer length.
Checking only the one-shorter prefix is enough, because that prefix is in the set only if its own prefix was, and so on down to one letter.
Example: in ["a", "banana", "app", "appl", "ap", "apply", "apple"] the sorted order is a, ap, app, appl, apple, apply, banana. Each word through apply extends the previous chain, banana is skipped because banan is missing, and apple stays the best because apply is not longer.
Complexity: O(m · n log n) time, where n is the number of words and m is the length of the longest word (each comparison, prefix and set lookup costs O(m)), and O(m · n) space for the set.
class Solution:
def longestWord(self, words: List[str]) -> str:
# In sorted order, every prefix of a word comes before the word itself.
words = sorted(words)
buildable = {""} # words that can be built one character at a time
best = ""
for word in words:
if word[:-1] in buildable:
buildable.add(word)
# Only a strictly longer word replaces best, so ties keep the smaller one.
if len(word) > len(best):
best = word
return best
Now write it from memory
Close the write-up and solve it yourself against the tests.