Minimize length of prefix of string S containing all characters of another string T | Python3 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
def getPrefixLength ( srcStr , targetStr ) : NEW_LINE INDENT if ( len ( targetStr ) == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT srcStr = srcStr . lower ( ) NEW_LINE targetStr = targetStr . lower ( ) NEW_LINE dictCount = dict ( [ ] ) NEW_LINE nUnique = 0 NEW_LINE for ch in targetStr : NEW_LINE INDENT if ( ch not in dictCount ) : NEW_LINE INDENT nUnique += 1 NEW_LINE dictCount [ ch ] = 0 NEW_LINE DEDENT dictCount [ ch ] += 1 NEW_LINE DEDENT for i in range ( len ( srcStr ) ) : NEW_LINE INDENT ch = srcStr [ i ] NEW_LINE if ( ch not in dictCount ) : NEW_LINE INDENT continue NEW_LINE DEDENT dictCount [ ch ] -= 1 NEW_LINE if ( dictCount [ ch ] == 0 ) : NEW_LINE INDENT nUnique -= 1 NEW_LINE DEDENT if ( nUnique == 0 ) : NEW_LINE INDENT return ( i + 1 ) NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " MarvoloGaunt " NEW_LINE T = " Tom " NEW_LINE print ( getPrefixLength ( S , T ) ) NEW_LINE DEDENT