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.
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
1. sub-string’s distinct characters is equal to maximum distinct characters
2. sub-sting’s length should be minimum .
Time Complexity : O(n^3)
The length of the smallest substring consisting of maximum distinct characters : 5
Method 2 (Efficient)
- Count all distinct characters in given string.
- Maintain a window of characters. Whenever the window contains all characters of given string, we shrink the window from left side to remove extra characters and then compare its length with smallest window fount so far.
Please refer Smallest window that contains all characters of string itself for implementation and more details.
Asked In : DailyHunt
This article is contributed by Harshit Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Maximum count of sub-strings of length K consisting of same characters
- Minimum length substring with exactly K distinct characters
- Maximum length substring having all same characters after k changes
- Length of the longest substring without repeating characters
- Smallest length string with repeated replacement of two distinct adjacent
- Lexicographically smallest substring with maximum occurrences containing a's and b's only
- Maximum length substring with highest frequency in a string
- Maximum length palindromic substring such that it starts and ends with given char
- Maximum length palindrome that can be created with characters in range L and R
- Generate a string consisting of characters 'a' and 'b' that satisfy the given conditions
- Maximum length of balanced string after swapping and removal of characters
- Length of the largest substring which have character with frequency greater than or equal to half of the substring
- Find distinct characters in distinct substrings of a string
- Replace minimal number of characters to make all characters pair wise distinct
- String with k distinct characters and no same characters adjacent