Number of index pairs such that s [ i ] and s [ j ] are anagrams | Java program to find number of pairs of integers i , j such that s [ i ] is an anagram of s [ j ] . ; 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
import java . util . * ; class GFG { static int anagram_pairs ( String [ ] s , int n ) { Map < String , Integer > mp = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { char [ ] chArr = s [ i ] . toCharArray ( ) ; Arrays . sort ( chArr ) ; s [ i ] = new String ( chArr ) ; if ( mp . containsKey ( s [ i ] ) ) { mp . put ( s [ i ] , mp . get ( s [ i ] ) + 1 ) ; } else { mp . put ( s [ i ] , 1 ) ; } } int ans = 0 ; for ( Map . Entry < String , Integer > i : mp . entrySet ( ) ) { int k = i . getValue ( ) ; ans += ( k * ( k - 1 ) ) / 2 ; } return ans ; } public static void main ( String [ ] args ) { String [ ] s = { " aaab " , " aaba " , " baaa " , " cde " , " dec " } ; int n = s . length ; System . out . println ( anagram_pairs ( s , n ) ) ; } }