Find the longest substring with k unique characters in a given string | Javascript program to find the longest substring with k unique characters in a given string ; This function calculates number of unique characters using a associative array count [ ] . Returns true if no . of characters are less than required else returns false . ; Return true if k is greater than or equal to val ; Finds the maximum substring with exactly k unique chars ; Number of unique characters ; Traverse the string , Fills the associative array count [ ] and count number of unique characters ; If there are not enough unique characters , show an error message . ; Otherwise take a window with first element in it . start and end variables . ; Also initialize values for result longest window ; Initialize associative array count [ ] with zero ; put the first character ; Start from the second character and add characters in window according to above explanation ; Add the character ' s [ i ] ' to current window ; If there are more than k unique characters in current window , remove from left side ; Update the max window size if required ; Driver Code
let MAX_CHARS = 26 ; function isValid ( count , k ) { let val = 0 ; for ( let i = 0 ; i < MAX_CHARS ; i ++ ) { if ( count [ i ] > 0 ) { val ++ ; } } return ( k >= val ) ; } function kUniques ( s , k ) { let u = 0 ; let n = s . length ; let count = new Array ( MAX_CHARS ) ; for ( let i = 0 ; i < MAX_CHARS ; i ++ ) { count [ i ] = 0 ; } for ( let i = 0 ; i < n ; i ++ ) { if ( count [ s [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] == 0 ) { u ++ ; } count [ s [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] ++ ; } if ( u < k ) { document . write ( " " ) ; return ; } let curr_start = 0 , curr_end = 0 ; let max_window_size = 1 ; let max_window_start = 0 ; for ( let i = 0 ; i < MAX_CHARS ; i ++ ) { count [ i ] = 0 ; } count [ s [ 0 ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] ++ ; for ( let i = 1 ; i < n ; i ++ ) { count [ s [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] ++ ; curr_end ++ ; while ( ! isValid ( count , k ) ) { count [ s [ curr_start ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] -- ; curr_start ++ ; } if ( curr_end - curr_start + 1 > max_window_size ) { max_window_size = curr_end - curr_start + 1 ; max_window_start = curr_start ; } } document . write ( " " + s . substring ( max_window_start , max_window_start + max_window_size + 1 ) + " " + max_window_size ) ; } let s = " " ; let k = 3 ; kUniques ( s , k ) ;