Minimize length of prefix of string S containing all characters of another string T | JavaScript program for the above approach ; Base Case - if T is empty , it matches 0 length prefix ; Convert strings to lower case for uniformity ; Update dictCount to the letter count of T ; If new character is found , initialize its entry , and increase nUnique ; Increase count of ch ; Iterate from 0 to N ; i - th character ; Skip if ch not in targetStr ; Decrease Count ; If the count of ch reaches 0 , we do not need more ch , and can decrease nUnique ; If nUnique reaches 0 , we have found required prefix ; Otherwise ; Driver code
function getPrefixLength ( srcStr , targetStr ) { if ( targetStr . length === 0 ) return 0 ; srcStr = srcStr . toLowerCase ( ) ; targetStr = targetStr . toLowerCase ( ) ; var dictCount = { } ; var nUnique = 0 ; for ( const ch of targetStr ) { if ( dictCount . hasOwnProperty ( ch ) !== true ) { nUnique += 1 ; dictCount [ ch ] = 0 ; } dictCount [ ch ] += 1 ; } for ( var i = 0 ; i < srcStr . length ; i ++ ) { var ch = srcStr [ i ] ; if ( dictCount . hasOwnProperty ( ch ) !== true ) continue ; dictCount [ ch ] -= 1 ; if ( dictCount [ ch ] === 0 ) nUnique -= 1 ; if ( nUnique === 0 ) return i + 1 ; } return - 1 ; } var S = " " ; var T = " " ; document . write ( getPrefixLength ( S , T ) ) ;