
1) wordFilter(‘WORDS’): Add this ‘WORDS’ array/list into ‘PRE_SUF_SEARCH’.
2) find(‘PREFIX’, ‘SUFFIX’): Return the index of the word that is present in ‘PRE_SUF_SEARCH’ having prefix as ‘PREFIX’ and the suffix as ‘SUFFIX’.
1) If there is more than one valid index in ‘PRE_SUF_SEARCH’ for the word, then return the largest possible index.
2) If there is no such word present in the ‘PRE_SUF_SEARCH’, then return -1.
3) ‘WORDS’ array/list contains only lowercase English alphabets.
‘PRE_SUF_SEARCH’ = [“apple”, “mango”, “banana”].
Query_1: find(‘a’, ‘e’).
We have to find the index of the largest possible word that starts with ‘a’ and ends with ‘e’.
Here we have only one word ‘apple’ present in ‘PRE_SUF_SEARCH’ and satisfy this condition. So we return 0.
The first line of input contains an integer ‘T’ which denotes the number of test cases or queries to be run. Then the test cases follow.
The first line of each test case contains an integer ‘N’ representing the number of words in the ‘WORDS’.
The next line of each test case contains ‘N’ single space-separated words representing the elements of ‘PRE_SUF_SEARCH’.
The next line of each test case contains an integer ‘Q’ representing the number of times the function find(‘PREFIX’, ‘SUFFIX’) call.
The next line of each test case contains two words representing the ‘PREFIX’ and ‘SUFFIX’.
For each test case, print a single line containing a single integer denoting the largest index of the word that satisfies the above conditions.
The output of each test case will be printed in a separate line.
You don’t need to print anything; It has already been taken care of. Just implement the given function.
1 <= ‘T’ <= 100
1 <= ‘N’ <= 10000
1 <= | ‘WORDS[i]’ | <= 10
1 <= ‘Q’ <= 10000
1 <= | ‘PREFIX’ |, | ‘SUFFIX’ | <= 10
Where ‘T’ denotes the total number of test cases, ‘N’ represents the number of words in ‘WORDS’, and | ‘ WORDS’ | indicates the size of each word, ‘Q’ represents the number of times the function find(‘PREFIX’, ‘SUFFIX’) call and ‘PREFIX’ and ‘SUFFIX’ represents the prefix and suffix of the word that is to be searched in ‘PRE_SUF_SEARCH’.
Time limit: 1 sec.
First, we will implement the wordFilter function. We will find all the prefixes and suffixes and concatenate them by adding a special character i.e ‘#’ between them. Then store this word in the HashMap ‘ALL_POSS_PRE_SUF_COMB’ with the index number as the value of this HashMap.
Then we implement the find function. We simply check if the word ‘PREFIX’ + ‘#’ + ‘SUFFIX’ is present in the HashMap ‘ALL_POSS_PRE_SUF_COMB’ or not. If this word is not present in the HashMap return -1.
We declare an array/list ‘ALL_INPUT_WORDS’ in which we store all words in the wordFilter function.
Then in the find function, we traverse the ‘ALL_INPUT_WORDS’ from reverse order and check for each word that it contains ‘PREFIX’ as a prefix and ‘SUFFIX’ as a suffix.
Here is the algorithm: