If the given string is S = "abcba", then the possible substrings are "abc" and "cba". As "abc" starts with a lower index (i.e. 0, "cba" start with index 2), we will print "abc" as our shortest substring that contains all characters of 'S'.
The only line of input contains a string 'S' i.e. the given string.
The only line of output contains a string i.e. the shortest substring of 'S' which contains all the characters of 'S' at least once.
You are not required to print the expected output, it has already been taken care of. Just implement the function.
1 <= N <= 10^5
'S' only contains lowercase English-Alphabet letters.
Where 'S' is the given string and ‘N’ is the length of ‘S’.
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 this many distinct characters at least once.
We can naively check all substrings by two nested loops and maintain a count of 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.
We will keep track of the minimum length substring obtained so far and only update it when we find a substring of a smaller length.
Here, is the complete algorithm-