You are given a string ‘S’ and a set of words named ‘Dictionary’. You can perform the operation of breaking the given string 'S', in any possible way and divide the given string into any number of subparts. Your task is to break the given string 'S', such that all the subparts are present in the Dictionary. You just need to tell the minimum number of times you need to break the string 'S' in order to accomplish the above task.
Note:1. If string 'S' is already present in the dictionary, then you don’t need to break the string and you can print 0 in such cases.
2. If it is impossible to complete the given task, then print -1.
3. All the characters of string 'S' and words inside the Dictionary only contain Uppercased English Alphabets.
The first line of the input contains an integer 'T', denoting the number of test cases.
The first line of each test case contains a string 'S', denoting the given string.
The second line of each test case contains an integer 'N', denoting the size of the given set of words.
The next 'N' lines contain a string denoting the ith word in the dictionary.
Output format:
For each test case print, the minimum number of times given string 'S' need to be broken in such a way that all the subparts are present in the Dictionary. In cases, when it is impossible to break string S, print -1.
Print the output of each testcase in a separate line.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 50
1 <= N <= 10^4
1 <= |S| <= 50
1 <= |word[i]| <= 50
‘A’ <= S[i] <= ‘Z’
Where |S| denotes the length of the given string, |word[i]| denotes the length of the ith word in the Dictionary.
It is guaranteed that all the words in the dictionary consist of only uppercase English alphabets from ‘A’ to ‘Z’.
Time Limit: 1 sec.
1
CODESTUDIO
5
COD
CODE
ESTU
DIO
STUDIO
1
We can break “CODESTUDIO” once and get subparts as “CODE” and “STUDIO”.
1
BREAKME
3
BROKE
ME
BREAKM
-1
Since there is no way by which we can break the given string and their subparts will be present in the Dictionary.
Try all possible ways to break the string.
O((K!)*K), where K is the size of the given string.
As we are trying to break each substring at each possible point and redividing those substrings further in next calls, this will make a recursion tree of height K and number of calls to next substrings reduced by 1. Hence overall order of O(K!) operations are done. Also checking at each state whether current substring is part of the Dictionary or not takes O(K) time. Hence, the overall time complexity is O((K!)*K).
O(K), where K is the size of the given string.
As we are using recursion, so it will take O(K) of stack memory. Hence, the overall space complexity is O(K).