Check if two strings are k | Function to check k anagram of two strings ; First Condition : If both the strings have different length , then they cannot form anagram ; Converting str1 to Character Array arr1 ; Converting str2 to Character Array arr2 ; Sort arr1 in increasing order ; Sort arr2 in increasing order ; Iterate till str1 . length ( ) ; Condition if arr1 [ i ] is not equal to arr2 [ i ] then add it to list ; Condition to check if strings for K - anagram or not ; Driver code ; Function Call
function kAnagrams ( str1 , str2 , k ) { let flag = 0 ; let list = [ ] ; if ( str1 . length != str2 . length ) { return false ; } let arr1 = str1 . split ( ' ' ) ; let arr2 = str2 . split ( ' ' ) ; arr1 . sort ( ) ; arr2 . sort ( ) ; for ( let i = 0 ; i < str1 . length ; i ++ ) { if ( arr1 [ i ] != arr2 [ i ] ) { list . push ( arr2 [ i ] ) ; } } if ( list . length <= k ) flag = 1 ; if ( flag == 1 ) return true ; else return false ; } let str1 = " " ; let str2 = " " ; let k = 2 ; kAnagrams ( str1 , str2 , k ) ; if ( kAnagrams ( str1 , str2 , k ) == true ) document . write ( " " ) ; else document . write ( " " ) ;