You are on page 1of 2

/* C++ program to find the length of the smallest 

substring consisting of maximum distinct characters */


#include <bits/stdc++.h>
using namespace std;
  
#define NO_OF_CHARS 256
  
// Find maximum distinct characters in any string
int max_distinct_char(string str, int n){
  
    // Initialize all character's count with 0
    int count[NO_OF_CHARS] = {0};
      
    // Increase the count in array if a character
    // is found
    for (int i = 0; i < n;  i++)
        count[str[i]]++;
      
    int max_distinct = 0;
    for (int i = 0; i < NO_OF_CHARS;  i++)
        if (count[i] != 0)      
            max_distinct++;     
      
    return max_distinct;
}
  
int smallesteSubstr_maxDistictChar(string str){
  
    int n = str.size();     // size of given string
  
    // Find maximum distinct characters in any string
    int max_distinct = max_distinct_char(str, n);
    int minl = n;   // result
      
    // Brute force approch to find all substrings
    for (int i=0 ;i<n ;i++){
        for (int j=0; j<n; j++){
            string subs =  str.substr(i,j);
            int subs_lenght = subs.size();
            int sub_distinct_char = max_distinct_char(subs, subs_lenght); 
              
            // We have to check here both conditions together
            // 1. substring's distinct characters is equal
            //    to maximum distinct characters
            // 2. substing's length should be minimum 
            if (subs_lenght < minl && max_distinct == sub_distinct_char){
                minl = subs_lenght;
            }
        }
    }
    return minl;
}
  
/* Driver program to test above function */
int main()
{
    // Input String
    string str = "AABBBCBB";
      
    int len =  smallesteSubstr_maxDistictChar(str);
    cout << " The length of the smallest substring"
            " consisting of maximum distinct "
            "characters : " << len;
    return 0;
}

You might also like