


If there are more than one substring with the shortest length, then find one which appears earlier in the string ‘S’ i.e. substring whose starting index is lowest.
If the given string ‘S’ = "abcba", then the possible substrings having all the characters of ‘S’ at least once and of minimum length are "abc" and "cba".
As "abc" starts with a lower index (i.e. 0, "cba" starts with index 2), we will return the string "abc" as our shortest substring that contains all characters of 'S'.
The first line of input contains an integer 'T' which denotes the number of test cases or queries to be run. Then each test case follows.
The first and the only line of each test case contains a single string 'S'.
For each test case, print a single line containing a string i.e. the shortest substring of 'S' which contains all the characters of 'S' at least once.
You don’t need to print the output, it has already been taken care of. Just implement the given function.
1 <= T <= 10 ^ 2
1 <= N <= 5 * (10 ^ 3)
S[i] = [a - z]
Where 'T' denotes the number of test cases and ‘N’ is the length of the given string ‘S’.
The given string 'S' consists of only English lowercase alphabets.
Time Limit: 1 sec
The problem boils down to counting distinct characters that are present in the string and then finding the minimum length substring that contains distinct characters at least once.
We can check for all substrings with two nested iterations and maintain a 'COUNT' for distinct characters for each substring with the help of a hashmap. There are many methods for maintaining this 'COUNT' with a hashmap, like the size of the hashmap or maintaining the 'COUNT' variable, etc.
Whenever the count of distinct characters for a substring equals the count of distinct characters in the given string, we process this substring. We will choose the minimum length substring out of all these substrings.
The idea is to use two pointers technique with a sliding window of variable length. The current window will be our current processing substring.
If the count of distinct characters of the current window is equal to that of the given string, it makes no sense in expanding the window (because the count will remain the same in doing so).
Similarly, if the count of the distinct characters is less than that of the given string, there is no benefit in shrinking the window.
We will keep track of the minimum length substring obtained so far and only update it when we find a substring of smaller length.