You are given an array/list of words ‘ARR’. Your task is to find all the words having the longest length which can be made from some other words on the list.
Note :
Return the list of all those words sorted in alphabetical. Return an empty list in case there are no such words
For Example :
Input: cat, banana, dog, nana, my, walk, walker, baby, dogwalkers, s, babymybaby
Output: babymybaby dogwalkers
Here in the given list of words, you can see that the words babymybaby, dogwalkers contain the words present in the list i.e. ‘s’, 'dog’, ‘walker’,‘baby’ and ‘my’ and both are of the same length.
Input format :
The first line contains the integer 'N', denoting the number of words that you will be given. Then N lines follow.
Each of the next 'N' lines contains a word denoting the elements of the word ARR.
Output format :
For the given list of ‘N’ words, print all such words in lexicographical order.
Note :
You do not need to print anything. It has already been taken care of. Just implement the given function.
Constraints :
1 <= N <= 1000
1 <= length of longest word <= 100
Where ‘N’ is the given list of words.
Time limit: 1 second
5
test
tester
testertest
testing
testingtester
testingtester
Here in the given list of words, you can see that the word ‘testingtester’ contains both the words present in the list i.e. testing and tester.
11
cat
banana
dog
nana
my
walk
walker
baby
dogwalkers
s
babymybaby
babymybaby dogwalkers
Can we recursively search for finding the longest word which would be comprised of words from the list to solve this problem?
The key observation here is to notice a simple fact that the longest word would be the one whose substring splits in all possible ways are also present in the list.
The algorithm for the same can be as follows:-
Steps:
O(N * L * L), where ‘N’ is the number of words present in that list (array) and ‘L’ is the length of the longest word.
Now, since there are N iterations in total each for L splits in each possible ways. And for each possible substring match in the list we call recursively for the remaining (L-1) length of the word. So the time complexity grows by O(N * L * L).
O(N), where ‘N’ is the number of words present in that list (array).
Since a set of upto ‘N’ words is being used for looking up elements present in the given list. So the space used here is O(N).