- Related Questions & Answers
- Length of longest string chain in JavaScript
- Program to find number of boxes that form longest chain 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 palindromic subsequence in Python
- Program to find length of longest word that can be formed from given letters in python
- Word Ladder (Length of shortest chain to reach a target word) in C++
- Program to find length of longest circular increasing subsequence in python
- C++ program for length of the longest word in a sentence
- Program to find length of longest alternating inequality elements sublist in Python

- 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 valid words, and have a string s also, we have to find the length of the longest chain of diminishing words that can be generated by starting at s and removing single letters and still make valid words.

So, if the input is like words = ["lii", "limit", "limi", "li", "coffee", "jug", "pool", "type"] s = "limit", then the output will be 4, as we can make the chain, starting from the word "limit", "limit" -> "limi" -> "lii" -> "li".

To solve this, we will follow these steps

Define a function solve() . This will take words, s

max_num := 0

for each i in words, do

if i is same as s, then

for j in range 0 to size of s, do

max_num := maximum of 1 + solve(words, s[from index 0 to j-1] concatenate s[from index j + 1 to end]) and max_num

return max_num

class Solution: def solve(self, words, s): max_num = 0 for i in words: if i == s: for j in range(len(s)): max_num = max(1 + self.solve(words, s[:j] + s[j + 1 :]), max_num) return max_num ob = Solution() words = ["lii", "limit", "limi", "li", "coffee", "jug", "pool", "type"] s = "limit" print(ob.solve(words, s))

["lii", "limit", "limi", "li", "coffee", "jug", "pool", "type"],"limit"

4

Advertisements