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 (*) which can match any character. 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" with length 6.

Algorithm

To solve this, we will follow these steps ?

  • has := a map containing letters and frequencies of each element in letters
  • Define a function valid() that takes a string 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, return maximum of all elements in the list [size of word for all word in words when word is valid]

Example

Let us see the following implementation to get better understanding ?

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))

The output of the above code is ?

6

How It Works

The solution works by counting available letters using Counter. For each word, we check if it can be formed by ?

  • Counting required letters for the word
  • Calculating how many extra letters we need beyond what's available
  • Using asterisk (*) characters as wildcards to fill the gaps

Alternative Approach

Here's a more readable version without using a class ?

from collections import Counter

def find_longest_word(words, letters):
    available = Counter(letters)
    
    def can_form_word(word):
        required = Counter(word)
        missing_chars = 0
        
        for char, count in required.items():
            if available[char] < count:
                missing_chars += count - available[char]
        
        return missing_chars <= available.get('*', 0)
    
    valid_words = [word for word in words if can_form_word(word)]
    return max(len(word) for word in valid_words) if valid_words else 0

# Test the function
words = ["prince", "rice", "price", "limit", "hello"]
letters = "*r**ce*"
result = find_longest_word(words, letters)
print(f"Length of longest word: {result}")
Length of longest word: 6

Conclusion

This algorithm efficiently finds the longest formable word by using Counter to track letter frequencies and asterisks as wildcards. The time complexity is O(n * m) where n is the number of words and m is the average word length.

Updated on: 2026-03-25T12:53:43+05:30

427 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements