Program to find length of longest word that can be formed from given letters in python

Suppose we have a list of words and a string called letters, we have to find the size of the longest word that can be made by rearranging the given letters. In the letters there may be asterisk character (*) it can match any character. And it is not necessary to use all the letters.

So, if the input is like words = ["prince", "rice", "price", "limit", "hello"] letters = "*r**ce*", then the output will be 6, as the longest word we can make is "prince" the length is 6.

To solve this, we will follow these steps:

  • has := a map containing letters and frequencies of each element in letters
  • Define a function valid() . This will take s
  • need := a map containing letters and frequencies of each element in s
  • extra := sum of all elements of (maximum of 0 and need[char] - has[char] for all char in need)
  • return true when extra <= has["*"]
  • From the main method do the following:
  • return maximum of all elements in the list [size of word for all word in words when word is valid]

Let us see the following implementation to get better understanding:


Live Demo

from collections import Counter

class Solution:
   def solve(self, words, letters):
      has = Counter(letters)

      def valid(s):
         need = Counter(s)
         extra = sum([max(0, need[char] - has[char]) for char in need])
         return extra <= has["*"]

      return max([len(word) for word in words if valid(word)])

ob = Solution()
words = ["prince", "rice", "price", "limit", "hello"]
letters = "*r**ce*"
print(ob.solve(words, letters))


["prince", "rice", "price", "limit", "hello"], "*r**ce*"