Length of the smallest sub-string consisting of maximum distinct characters
Last Updated :
30 Jan, 2023
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
- sub-string’s distinct characters is equal to maximum distinct characters
- sub-string’s length should be minimum.
Implementation:
C++
Java
Python3
C#
PHP
Javascript
Output
The length of the smallest substring consisting of maximum distinct characters : 5
Time Complexity : O(n3)
Auxiliary Space: O(n)
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 found so far.
Implementation:
C++
Java
Python3
C#
using System;
using System.Collections.Generic;
class GFG
{
static int MAX_CHARS = 256;
static int max_distinct_char(String str, int n)
{
int [] count = new int [MAX_CHARS];
int max_distinct = 0;
for ( int i = 0; i < n; i++) {
count[str[i]]++;
if (count[str[i]] == 1)
max_distinct++;
}
return max_distinct;
}
static int smallestSubstr_maxDistictChar(String str)
{
int n = str.Length;
int unique = max_distinct_char(str, n);
int res = int .MaxValue;
Dictionary< char , int > mp = new Dictionary< char , int >();
int j = 0;
for ( int i = 0; i < n; i++) {
if (mp.ContainsKey(str[i]))
mp[str[i]]++;
else
mp.Add(str[i], 1);
while (mp.Count == unique && mp[str[j]] > 1)
{
mp[str[j]]--;
j++;
}
if (mp.Count == unique)
res = Math.Min(i - j + 1, res);
}
return res;
}
static public void Main(String[] args)
{
String str = "AABBBCBB" ;
int len = smallestSubstr_maxDistictChar(str);
Console.WriteLine( " The length of the smallest substring"
+ " consisting of maximum distinct "
+ "characters : " +len);
}
}
|
Javascript
Output
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
Share your thoughts in the comments
Please Login to comment...