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 email@example.com. 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
- 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
- Generate a string consisting of characters 'a' and 'b' that satisfy the given conditions
- Replace minimal number of characters to make all characters pair wise distinct
- String with k distinct characters and no same characters adjacent
- Longest substring having K distinct vowels
- Count number of Distinct Substring in a String
- Permutation of a string with maximum number of characters greater than its adjacent characters
- Print Longest substring without repeating characters
- Searching characters and substring in a String in Java
- Minimum characters to be replaced to remove the given substring