Minimize length of Substrings containing at least one common Character | Function to check and return if subStrings of length mid has a common character a ; Length of the String ; Initialise the first occurrence of character a ; Check that distance b / w the current and previous occurrence of character a is less than or equal to mid ; If distance exceeds mid ; Function to check for all the alphabets , if subStrings of length mid have a character common ; Check for all 26 alphabets ; Check that char i + a is common in all the subStrings of length mid ; If no characters is common ; Function to calculate and return the minm length of subStrings ; Initialise low and high ; Perform binary search ; Update mid ; Check if one common character is present in the length of the mid ; Returns the minimum length that contain one common character ; Function to check if all characters are distinct ; Driver Code
function check ( str , mid , a ) { var n = str . length ; var previous = - 1 , i ; for ( i = 0 ; i < n ; ++ i ) { if ( str [ i ] === a ) { if ( i - previous > mid ) { return false ; } previous = i ; } } if ( i - previous > mid ) return false ; else return true ; } function possible ( str , mid ) { for ( var i = 0 ; i < 26 ; ++ i ) { if ( check ( str , mid , String . fromCharCode ( i + " " . charCodeAt ( 0 ) ) ) ) return true ; } return false ; } function findMinLength ( str ) { var low = 1 , high = str . length ; while ( low <= high ) { var mid = parseInt ( ( low + high ) / 2 ) ; if ( possible ( str , mid ) ) high = mid - 1 ; else low = mid + 1 ; } return high + 1 ; } function ifAllDistinct ( str ) { var s = new Array ( ) ; var temp = str . split ( " " ) ; for ( const c of temp ) { s . push ( c ) ; } var set = new Set ( s ) ; return set . size === str . length ; } var str = " " ; if ( ifAllDistinct ( str ) ) document . write ( - 1 + " " ) ; else document . write ( findMinLength ( str . split ( " " ) ) ) ;