Program to find the length of the longest, that can be made using given letters in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of strings called words and another string called letters, we have to find the length of longest string in words that can be formed from characters in letters. If no word can be formed, then return 0. Here we cannot reuse letters.

So, if the input is like words = ["dog", "cat", "rat", "bunny", "lion", "bat"], letters = "gabctnyu", then the output will be 3, as we can make words "cat", or "bat", so the maximum length is 3.

To solve this, we will follow these steps −

  • ref := a map with letters, and their frequencies
  • max := 0
  • for each word in words, do
    • w := a map with letters of word, and their frequencies
    • l := size of word
    • counter := 0
    • for each k in w, do
      • if w[k] <= ref[k], then
        • counter := counter + 1
      • otherwise,
        • come out from the loop
    • if l > max and size of w is same as counter, then
      • max := l
  • return max

Let us see the following implementation to get better understanding −

Example

 Live Demo

from collections import Counter
class Solution:
   def solve(self, words, letters):
      ref = Counter(letters)
      max = 0
      for word in words :
         w = Counter(word)
         l = len(word)
         counter = 0
         for k in w :
            if w[k] <= ref[k]:
               counter+=1
               pass
            else :
               break
               if l > max and len(w) == counter:
                  max = l
         return max
ob = Solution()
words = ["dog", "cat", "rat", "bunny", "lion", "bat"]
letters = "gabctnyu" print(ob.solve(words, letters))

Input

["dog", "cat", "rat", "bunny", "lion", "bat"], "gabctnyu"

Output

3
raja
Published on 05-Oct-2020 15:39:56
Advertisements