Find the smallest window in a string containing all characters of another string | javascript program to find smallest window containing all characters of a pattern . ; Function to find smallest window containing all characters of ' pat ' ; Check if string ' s ▁ length ▁ is ▁ ▁ less ▁ than ▁ pattern ' s length . If yes then no such window can exist ; Store occurrence ofs characters of pattern ; Start traversing the string Count of characters ; Count occurrence of characters of string ; If string ' s ▁ char ▁ matches ▁ ▁ with ▁ pattern ' s char then increment count ; If all the characters are matched ; Try to minimize the window ; update window size ; If no window found ; Return substring starting from start_index and length min_len ; Driver Method
var no_of_chars = 256 ; function findSubString ( str , pat ) { var len1 = str . length ; var len2 = pat . length ; if ( len1 < len2 ) { document . write ( " " ) ; return " " ; } var hash_pat = Array . from ( { length : no_of_chars } , ( _ , i ) => 0 ) ; var hash_str = Array . from ( { length : no_of_chars } , ( _ , i ) => 0 ) ; for ( var i = 0 ; i < len2 ; i ++ ) hash_pat [ pat . charAt ( i ) . charCodeAt ( 0 ) ] ++ ; var start = 0 , start_index = - 1 , min_len = Number . MAX_VALUE ; var count = 0 ; for ( var j = 0 ; j < len1 ; j ++ ) { hash_str [ str . charAt ( j ) . charCodeAt ( 0 ) ] ++ ; if ( hash_str [ str . charAt ( j ) . charCodeAt ( 0 ) ] <= hash_pat [ str . charAt ( j ) . charCodeAt ( 0 ) ] ) count ++ ; if ( count == len2 ) { while ( hash_str [ str . charAt ( start ) . charCodeAt ( 0 ) ] > hash_pat [ str . charAt ( start ) . charCodeAt ( 0 ) ] || hash_pat [ str . charAt ( start ) . charCodeAt ( 0 ) ] == 0 ) { if ( hash_str [ str . charAt ( start ) . charCodeAt ( 0 ) ] > hash_pat [ str . charAt ( start ) . charCodeAt ( 0 ) ] ) hash_str [ str . charAt ( start ) . charCodeAt ( 0 ) ] -- ; start ++ ; } var len_window = j - start + 1 ; if ( min_len > len_window ) { min_len = len_window ; start_index = start ; } } } if ( start_index == - 1 ) { document . write ( " " ) ; return " " ; } return str . substring ( start_index , start_index + min_len ) ; } var str = " " ; var pat = " " ; document . write ( " " + findSubString ( str , pat ) ) ;