VOOZH about

URL: https://www.geeksforgeeks.org/dsa/length-smallest-sub-string-consisting-maximum-distinct-characters/

⇱ Length of the smallest sub-string consisting of maximum distinct characters - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Length of the smallest sub-string consisting of maximum distinct characters

Last Updated : 5 Aug, 2024

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. 

👁 Image

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 

  1. sub-string's distinct characters is equal to maximum distinct characters 
  2. sub-string's length should be minimum. 

Implementation:


Output
 The length of the smallest substring consisting of maximum distinct characters : 5

Time Complexity :O(n3)
Auxiliary Space: O(n) 

Method 2 (Efficient)

  1. Count all distinct characters in given string.
  2. 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:


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 

Comment