Number of index pairs such that s [ i ] and s [ j ] are anagrams | Function to find number of pairs of integers i , j such that s [ i ] is an anagram of s [ j ] . ; To store count of strings ; Traverse all strings and store in the map ; Sort the string ; Store in the map ; To store the number of pairs ; Traverse through the map ; Count the pairs for each string ; Return the required answer ; Driver code ; Function call
function anagram_pairs ( s , n ) { let mp = new Map ( ) ; for ( let i = 0 ; i < n ; i ++ ) { let chArr = s [ i ] . split ( " " ) ; chArr . sort ( ) ; s [ i ] = chArr . join ( " " ) ; if ( mp . has ( s [ i ] ) ) { mp . set ( s [ i ] , mp . get ( s [ i ] ) + 1 ) } else { mp . set ( s [ i ] , 1 ) } } let ans = 0 ; for ( let i of mp ) { let k = i [ 1 ] ; ans += Math . floor ( ( k * ( k - 1 ) ) / 2 ) ; } return ans ; } let s = [ " " , " " , " " , " " , " " ] ; let n = s . length ; document . write ( anagram_pairs ( s , n ) ) ;