Check if two strings are k | Optimized Javascript 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 [ i ] 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
let MAX_CHAR = 26 ; function areKAnagrams ( str1 , str2 , k ) { let n = str1 . length ; if ( str2 . length != n ) return false ; let hash_str1 = Array ( MAX_CHAR ) ; hash_str1 . fill ( 0 ) ; for ( let i = 0 ; i < n ; i ++ ) hash_str1 [ str1 [ i ] . charCodeAt ( ) - ' ' . charCodeAt ( ) ] ++ ; let count = 0 ; for ( let i = 0 ; i < n ; i ++ ) { if ( hash_str1 [ str2 [ i ] . charCodeAt ( ) - ' ' . charCodeAt ( ) ] > 0 ) hash_str1 [ str2 [ i ] . charCodeAt ( ) - ' ' . charCodeAt ( ) ] -- ; else count ++ ; if ( count > k ) return false ; } return true ; } let str1 = " " ; let str2 = " " ; let k = 2 ; if ( areKAnagrams ( str1 , str2 , k ) == true ) document . write ( " " ) ; else document . write ( " " ) ;