Number of index pairs such that s [ i ] and s [ j ] are anagrams | CPP 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int anagram_pairs ( vector < string > s , int n ) { map < string , int > mp ; for ( int i = 0 ; i < n ; i ++ ) { sort ( s [ i ] . begin ( ) , s [ i ] . end ( ) ) ; mp [ s [ i ] ] ++ ; } int ans = 0 ; for ( auto i = mp . begin ( ) ; i != mp . end ( ) ; i ++ ) { int k = i -> second ; ans += ( k * ( k - 1 ) ) / 2 ; } return ans ; } int main ( ) { vector < string > s = { " aaab " , " aaba " , " baaa " , " cde " , " dec " } ; int n = s . size ( ) ; cout << anagram_pairs ( s , n ) ; return 0 ; }