You are given a string “str”. Find the maximum number of non-empty substrings of “str” such that no two substrings overlap with each other and each substring that you select containing a letter ‘t’ must contain all the occurrences of ‘t’ in that substring.
A string ‘a’ is a substring of a string ‘b’ if ‘a’ can be obtained from ‘b’ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
Note:If there are multiple solutions of a string, return the string with minimum total length.
For Example :
Let str = abaccce
Now In this example, we can make a maximum of three substrings i.e. {‘b’, ‘ccc’, ‘e’}.
Note:
There can be one more solution with maximum substrings equal to three i.e. {‘aba’, ‘ccc’, ‘e’} but we have to select the substrings with minimum total length. So the final answer is {‘b’, ‘ccc’, ‘e’}.
The first line contains a single integer ‘T’ denoting the number of test cases to be run. Then the test cases follow.
The first and only line of each test case contains a string “str”.
Output Format :
For each test case, print a list of strings “ans”.
Output for each test case will be printed in a separate line.
Note :
You are not required to print anything; it has already been taken care of. Just implement the function and return the answer.
1 <= T <= 10
1 <= |str| <= 10^5, where |str| represents the length of the String str.
Time limit: 1 sec
2
ab
wxzxzz
a b
w xzxzz
For the first test case, there are two non-overlapping substrings satisfying the condition i.e. a, b.
For the second test case, we have to select the whole substring “xzxzz” for the final answer as we need to select all the occurrences of a letter in one substring. Hence the answer is w, xzxzz.
2
abc
xtx
a b c
t
For every substring try to minimize its length greedily by selecting a shorter substring having all the occurrences of all the letters in the string.
The approach is simple, take two arrays left and right which will store the first and last occurrences of every character of the string and we will check for each position of the string if it is the minimum possible substring satisfying the given conditions.
The steps are as follows:
O(|str|), where |str| is the length of the given string.
Since we are iterating through the string once.
Hence the total time complexity is O(|str|).
O( 1 ).
Since we are only storing the first and last indexes of 26 characters and no more space is used.
Hence the space complexity is O( 1 ).