- Related Questions & Answers
- Program to find length of longest word that can be formed from given letters in python
- Maximum number of parallelograms that can be made using the given length of line segments in C++
- Program to find length of longest sublist with given condition in Python
- Program to find length of longest Fibonacci subsequence from a given list in Python
- Program to find length of longest balanced subsequence in Python
- Program to find length of longest anagram subsequence in Python
- Program to find length of longest consecutive sequence in Python
- Program to find length of longest distinct sublist in Python
- Program to find length of longest increasing subsequence in Python
- Program to find length of longest palindromic substring in Python
- Program to find length of longest possible stick in Python?
- Program to find length of longest diminishing word chain in Python?
- Program to find length of longest circular increasing subsequence in python
- Program to find the length of longest substring which has two distinct elements in Python
- C# program to find the length of the Longest Consecutive 1’s in Binary Representation of a given integer

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 w[k] <= ref[k], then
- 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 −

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

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

3

Advertisements