Print all pairs of anagrams in a given array of strings | JavaScript program to find best meeting point in 2D array ; function to check whether two strings are anagram of each other ; Create two count arrays and initialize all values as 0 ; For each character in input strings , increment count in the corresponding count array ; If both strings are of different length . Removing this condition will make the program fail for strings like " aaca " and " aca " ; See if there is any non - zero value in count array ; This function prints all anagram pairs in a given array of strings ; Driver Code
let NO_OF_CHARS = 256 function areAnagram ( str1 , str2 ) { let count = [ ] ; for ( let i = 0 ; i < NO_OF_CHARS ; i ++ ) count [ i ] = 0 ; let i = 0 ; while ( i < ( str1 ) . length && i < ( str2 ) . length ) { count [ ord ( str1 [ i ] ) ] += 1 ; count [ ord ( str2 [ i ] ) ] -= 1 ; i += 1 ; } if ( ( str1 ) . length != ( str2 ) . length ) return false ; for ( let i = 0 ; i < NO_OF_CHARS ; i ++ ) { if ( count [ i ] ) return false ; return True ; } } function findAllAnagrams ( arr , n ) { for ( let i = 0 ; i < n ; i ++ ) { for ( let j = i + 1 ; j < n ; j ++ ) { if areAnagram ( arr [ i ] , arr [ j ] ) document . write ( arr [ i ] + " " + arr [ j ] ) } } } let arr = [ " " , " " , " " , " " , " " ] ; let n = ( arr ) . length ; findAllAnagrams ( arr , n ) ;