Longest Word in Dictionary in Python


Suppose we have a list of words representing an English Dictionary, we have to find the longest word in the given word list that can be built one character at a time by other words in words. If there is more than one possible answer, then return the longest word with the smallest lexicographical order. If there is no answer, then return the empty string.

So, if the input is like ["h","he","hel","hell", "hello"], then the output will be "hello"

To solve this, we will follow these steps −

  • trie := a new map
  • Define a function insert(). This will take word
  • now := trie
  • for each c in word, do
    • if c not in now −
      • now[c] = {'#', False}, then
    • now := now[c]
    • now['#'] := True
  • Define a function search() . This will take word
  • now := trie
  • for each c in word, do
    • if '#' in now and not now['#'] is True, then
      • return false
    • now := now[c]
    • return now['#']
  • for each word in words, do
    • call insert(word)
  • ans := blank string
  • for each word in words, do
    • if search(word) and(size of word > size of ans or (size of word is same as size of ans and word < ans)), then
      • ans := word
  • return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def longestWord(self, words):
      self.trie = {}
   def insert(word):
      now = self.trie
      for c in word:
         if c not in now: now[c] = {'#': False}
            now = now[c]
         now['#'] = True
   def search(word):
      now = self.trie
      for c in word:
         if '#' in now and not now['#']: return False
            now = now[c]
         return now['#']
         for word in words:
            insert(word)
         ans = ""
         for word in words:
            if (search(word) and (len(word) > len(ans) or (len(word) == len(ans) and word    < ans))):
         ans = word
      return ans
ob = Solution()
print(ob.longestWord(["h","he","hel","hell", "hello"]))

Input

["h","he","hel","hell", "hello"]

Output

hello

Updated on: 04-Jul-2020

344 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements