You are given an array 'arr' of strings, where each string consists of English lowercase letters.
A string chain of 'arr' is defined as:
(1) A sequence of string formed using elements of 'arr'.
(2) Every string in the sequence can be formed by inserting a lowercase English letter into the previous string (except the first string).
Find the length of the longest possible string chain of 'arr'.
Input: 'arr' = ["x", "xx", "y", "xyx"]
Output: 3
Explanation:
The longest possible string chain is “x” -> “xx” -> “xyx”.
The length of the given chain is 3, hence the answer is 3.
The first line of the input contains a single integer 'n' denoting the length of the 'arr'.
The next 'n' lines of the input contains elements of 'arr'.
Return the length of the longest possible string chain with strings chosen from the given array.
You don't need to print anything; it has already been taken care of. Just implement the function.
3
m
nm
mmm
2
2
In this testcase, the longest possible string chain is "m" -> "nm".
The length of the given chain is 2, hence the answer is 2.
5
a
bc
ad
adc
bcd
3
3
In this testcase, the longest possible string chain is “a” -> “ad” -> “adc”.
The length of the given chain is 3, hence the answer is 3.
Try to solve this in O(n*n*l), where 'n' is the size of array 'arr' and 'l' is the maximum length of a string in 'arr'.
1 ≤ n ≤ 300
1 ≤ arr[i].length ≤ 16
Time limit: 1 sec
Explore all the possibilities for each word.
The total number of states are approximately equal to N ^ N. Note that state denotes a function call to ‘rec()’. In this approach, we generate all possible chains starting from ARR[I].
At the i’th position, we will explore the longest string chain which would be possible starting from this string(i’th). We will take the maximum of the length of all string chains possible from ‘i’ equal to 0 to ‘N’ - 1.
The recursion tree for ‘ARR’ = [“x”, “xx”, “y”, “xyx”] will be :
The steps are as follows :
O( N ^ ( N + L ) ), where N is the length of the array and L is the max length of the string in the array.
For each of the strings in the array, we may have to explore all the remaining strings of the order ~N. The total number of states are approximately equal to N ^ N. Note that state denotes a function call to ‘rec()’. And every time we will also check for predecessor.
Hence the time complexity is O( N ^ ( N + L ) ).
O( N ^ 2 ), where N is the length of the array.
The maximum number of stack frames that could be present in memory at any point of time are ~N. And there will be N such recursive calls. Each function call take `O( N ) space and the maximum depth of the recursion tree is N.
Hence the space complexity is O( N ^ 2 ).