


If the array of strings is: {co, code, studio, codingninjas, coding, debug, coder, cipher}
Then the original cost of the array is 2 + 4 + 6 + 12 + 6 + 5 + 5 + 6 = 46.
If we select the new string as “cod” and delete the matching prefixes if exists then the array becomes: {co, e, studio, ingninjas, ing, debug, er, cipher}, and the cost now becomes: 2 + 1 + 6 + 9 + 3 + 5 + 2 + 6 = 34.
You can check for any other possible string, the cost will not become less than 34, hence the optimal answer for this case is “cod”.
The first line contains a single integer ‘T’ denoting the number of test cases, then each test case follows:
The first line of each test case contains a single integer ‘N’ denoting the length of the array of strings.
The next N lines each contain ‘Arr[i]’ consisting of lower case English alphabets, denoting the ith string in the array.
For each test case, print the string which minimizes the cost of the array of deletion of common prefixes.
Output for each test case will be printed in a separate line.
You are not required to print anything; it has already been taken care of. Just implement the function.
1 <= T <= 10
1 <= N <= 20
1 <= Arr[i].length <= 20
Time limit: 1 sec
For each string in the array consider each of its prefix string one by one, now check what will be the cost if the current prefix string is used to delete matching prefixes from all the strings in the array. Keep track of the prefix string that had the lowest cost and finally return that string.
The steps are as follows :
For each string in the array consider each of its prefix strings one by one and increment frequency associated with it in the hash-map.
Also pre-compute the original cost of the given array of strings, this cost is equal to the sum of the length of each string.
In the end, simply iterate the hash-map, for each prefix string if we use it then cost will be reduced by the length of the prefix string multiplied by its frequency from the original cost.
Find the optimal answer and return it.
The steps are as follows :