Check if two strings are k | Optimized Python3 program to check if two strings are k anagram or not . ; Function to check if str1 and str2 are k - anagram or not ; If both strings are not of equal length then return false ; Store the occurrence of all characters in a hash_array ; Store the occurrence of all characters in a hash_array ; Return true if count is less than or equal to k ; Driver code
MAX_CHAR = 26 ; NEW_LINE def areKAnagrams ( str1 , str2 , k ) : NEW_LINE INDENT n = len ( str1 ) ; NEW_LINE if ( len ( str2 ) != n ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT hash_str1 = [ 0 ] * ( MAX_CHAR ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT hash_str1 [ ord ( str1 [ i ] ) - ord ( ' a ' ) ] += 1 ; NEW_LINE DEDENT count = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( hash_str1 [ ord ( str2 [ i ] ) - ord ( ' a ' ) ] > 0 ) : NEW_LINE INDENT hash_str1 [ ord ( str2 [ i ] ) - ord ( ' a ' ) ] -= 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT if ( count > k ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE DEDENT str1 = " fodr " ; NEW_LINE str2 = " gork " ; NEW_LINE k = 2 ; NEW_LINE if ( areKAnagrams ( str1 , str2 , k ) == True ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT