![]() |
VOOZH | about |
Given a string of length N, find the length of the smallest sub-string consisting of maximum distinct characters. Note : Our output can have same character.
Examples:
Input : "AABBBCBB"
Output : 5
Input : "AABBBCBBAC"
Output : 3
Explanation : Sub-string -> "BAC"
Input : "GEEKSGEEKSFOR"
Output : 8
Explanation : Sub-string -> "GEEKSFOR"
Method 1 (Brute Force)
We can consider all sub-strings one by one and check for each sub-string both conditions together
Implementation:
The length of the smallest substring consisting of maximum distinct characters : 5
Time Complexity :O(n3)
Auxiliary Space: O(n)
Method 2 (Efficient)
Implementation:
The length of the smallest substring consisting of maximum distinct characters : 5
Time Complexity: O(n), As we doing linear operations on string.
Auxiliary Space: O(n), As constant extra space is used. The size of set and map can only go upto a maximum size of 256 which is a constant thus the extra space used is also constant.
Please refer Smallest window that contains all characters of string itself more details.
Asked In : DailyHunt