


The same word in the dictionary can be used multiple times to make sentences.
Assume that the dictionary does not contain duplicate words.
The first line contains an integer ‘T’ denoting the number of test cases.
Then the 'T' test cases follow.
The first line contains an integer value ‘K’ which denotes the size of the dictionary.
The second line contains ‘K’ non-empty, space separated strings denoting the words of the dictionary.
The third line contains a non-empty string ‘S’.
For each test case, print each possible sentence after adding spaces, in different lines.
The output of each test case is printed in a separate line.
1. You do not need to print anything, it has already been taken care of. Just implement the given function.
2. The order in which the output sentences are returned does not matter.
1 <= T <= 10
1 <= K <= 100
1 <= | word | <= 16
1 <= | S | <= 13
where |word| is the length of each word in the dictionary and |S| is the length of the string S.
Time Limit: 1 sec
We need to keep exploring the given string from current position ‘i’ to until we wouldn’t find a position such that substring ‘i’ to ‘j’ exists in the dictionary.
Algorithm:
We are solving this problem by solving its subproblems and then combining the solutions of those subproblems. If we analyze carefully, we will see that we are solving the same subproblems multiple times. Thus, this problem exhibits overlapping subproblems. Thus, in this approach, we will eliminate the need for solving the same subproblems again and again.
Suppose our string ‘S’ is “aakash”
The below figure shows some of the recursive calls made for the given problem.
As we can see, some subproblems are called multiple times.
Same subproblems are shown by the same color.
That’s why we are storing the solved subproblems in a map so that we don’t have to solve them again. Whenever a call is made to the solved subproblem, we will directly return the answer of that subproblem stored in the map.
The idea is to use Trie data structure.
A trie is a tree-like data structure whose nodes store the letters of an alphabet. By structuring the nodes in a particular way, words and strings can be retrieved from the structure by traversing down a branch path of the tree.
Using trie will help us to save time and space.
A sample trie formed by adding words ‘ate’, ‘ant’, ‘ants’, ‘bat’, ‘ball’, ‘and’ is shown below. The nodes with green color represent the end of the word.
Algorithm: